Skip to content

Structs

Openweb edited this page Oct 7, 2020 · 7 revisions

Go Structs

Struct is aggregate data types, that groups zero or named values (of arbitrary type) as a single entity. Each value is called a field.

  1. Fields are usually written one per line
  2. A field is exported if it begins with a capital letter
  3. Named struct can not have a filed with same type, instead use a pointer to it
  4. Zero value of struct is zero value of individual fields
  5. If all fields are comparable the struct is itself comparable
  6. Comparable structs can be used as map keys
  7. struct can have anonymous fields (struct embedding)
  8. Like array they are passed as values. So use pointers if need to be passed to functions

Struct Literals

Examples of struct literals are as under:

type Point struct {X, Y int} // Define struct
p := Point{X: 1, Y:2} // Specify key explicitly, any order
p1 := Point{1,2} // No keys specified, fields are assumed in order, X first then Y
pp1 := new(Point) // Get a pointer to struct, not initialed yet
*pp1 = Point{5,6} // Equivalent to definition below
pp := &Point{3,4}

Go play with struct definitions.

Struct Embedding

Anonymous struct definitions are used for simpler composition. Here is example of anonymous field from the book. Note that you can not have two anonymous fields of same type. In order to access them from outside the package all intermediary structs need to be Capitalized. Anonymous definitions do no have short-hand literal definitions.

type Point struct {
  X, Y int
}

Include Point in definition of Circle as anonymous field.

type Circle struct {
  Point
  Radius int
}

Use Circle in definition of wheel as anonymous field:

type Wheel struct {
  Circle
  Spokes int
}

Then we can refer to these as:

var w Wheel
w.X = 10; w.Y = 10; w.Radius = 20; w.Spokes = 30
// These are not allowed:
// w1 := Wheel{10, 10, 20, 30}
// s2 := Wheel{X:10, Y:10, Radius:20, Spokes:30}

It follows shape type structure, e:g:

 w := Wheel{Circle{Point{X: 10, Y:10}, 20}, 30}
 w1 := Wheel{
   Circle: Circle{
      Point: Point{X: 10, Y:10},
      Radius: 20,
   }
   Spokes: 30, // NOTE: Trailing comma
 }

Nameless fields

A struct may have nameless fields. You can use name of the type to access this. See example on playground.

type Celsius float64
type Farhenheit float64

type temp struct {
  Celsius    // Anonymous field, to access use name of type,  Celsius
  Fahrenheit // Anonymous field, to access use name of type,  Farhenheit
  float64    // Anonymous field, to access use name of type,  float64
}
Clone this wiki locally