官术网_书友最值得收藏!

Struct

A struct in Go is a data structure that is composed of fields, where each field has a type. Here is what a Go struct looks like:

type myStruct struct{
intField int
stringField string
sliceField []int
}

The preceding code creates a struct type that is called myStruct, which contains three fields:

  • intField of type int
  • stringField of type string
  • sliceField of type []int

You can then initialize and use that struct type in your code:

var s = myStruct{
intField: 3,
stringField: "three",
sliceField : []int{1,2,3},
}

The preceding method of initialization is also known as struct literals. There is a shorter version of it that looks like this:

var s = myStruct{3,"three",[]int{1,2,3}}

You can also use what is known as dot notation, which looks as follows:

var s = myStruct{}
s.intField = 3
s.stringField = "three"
s.sliceField= []int{1,2,3}

You can obtain a pointer to a struct by doing this:

var sPtr = &myStruct{
intField:3,
stringField:"three",
sliceField: []int{1,2,3},
}

A dot notation can be used with a Go struct pointer, since Go will understand what needs to be done without the need to do any pointer de-referencing:

var s = &myStruct{}
s.intField = 3
s.stringField = "three"
s.sliceField= []int{1,2,3}

If the Go struct field names start with lower case letters, they will not be visible to external packages. If you want your struct or its fields to be visible to other packages, start the struct and/or field name with upper case letters.

Now, let's talk about Go methods.

主站蜘蛛池模板: 南溪县| 中西区| 阜城县| 宜兴市| 石棉县| 荣昌县| 黑龙江省| 旺苍县| 南皮县| 阿勒泰市| 泽州县| 石柱| 宣武区| 岢岚县| 小金县| 东乌| 久治县| 兰考县| 宜良县| 平凉市| 涟源市| 梨树县| 嘉峪关市| 普陀区| 柳州市| 平舆县| 前郭尔| 嘉义市| 桂阳县| 封丘县| 海淀区| 温宿县| 盈江县| 玉门市| 马尔康县| 怀来县| 会理县| 汕头市| 武冈市| 靖边县| 固阳县|