struct

72 阅读1分钟

声明、使用

type Rectangle struct {
  length  float64
  breadth float64
}
var r Rectangle
r.length = 1
r.breadth = 1

or

r2 := Rectangle{length: 1, breadth: 1}

Creating a pointer struct instance

1.&

myRectangle := &Rectangle{length: 10, breadth: 5}
fmt.Println(myRectangle, *myRectangle) // &{10 5} {10 5}

2.new

myRectangle := new(Rectangle)
fmt.Println(myRectangle, *myRectangle) // &{0 0} {0 0}

Anonymous structs

Anonymous structs allow you to create structs inside functions and use them on the go

// creating a struct anonymously
circle := struct {
  radius float64
  color  string
}{
  radius: 10.6,
  color:  "green",
}

fmt.Println(circle)       // {10.6 green}
fmt.Println(circle.color) // green

struct methods

type Rectangle struct {
  length  float64
  breadth float64
}

func (r Rectangle) area() float64 {
  return r.length * r.breadth
}