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

Struct

In Go, a struct or data structure is a collection of variables. The variables can be of different types. We will look at an example of creating a custom struct type.

Go uses case-based scoping to declare a variable either public or private. Variables and methods that are capitalized are exported and accessible from other packages. Lowercase values are private and only accessible within the same package.

The following example creates a simple struct named Person and one named Hacker. The Hacker type has a Person type embedded within it. An instance of each type is then created and the information about them is printed to standard output:

package main

import "fmt"

func main() {
// Define a Person type. Both fields public
type Person struct {
Name string
Age int
}

// Create a Person object and store the pointer to it
nanodano := &Person{Name: "NanoDano", Age: 99}
fmt.Println(nanodano)

// Structs can also be embedded within other structs.
// This replaces inheritance by simply storing the
// data type as another variable.
type Hacker struct {
Person Person
FavoriteLanguage string
}
fmt.Println(nanodano)

hacker := &Hacker{
Person: *nanodano,
FavoriteLanguage: "Go",
}
fmt.Println(hacker)
fmt.Println(hacker.Person.Name)

fmt.Println(hacker)
}

You can create private variables by starting their name with a lowercase letter. I use quotation marks because private variables work slightly different than in other languages. The privacy works at the package level and not at the class or type level.

主站蜘蛛池模板: 石楼县| 九江县| 恩平市| 余姚市| 海原县| 乌鲁木齐县| 奇台县| 隆回县| 惠来县| 禄丰县| 内乡县| 大名县| 固镇县| 新竹市| 陆丰市| 冕宁县| 青阳县| 洛浦县| 西峡县| 田东县| 临夏县| 萝北县| 广德县| 南溪县| 黑山县| 常熟市| 雅江县| 玉树县| 固安县| 诏安县| 桂平市| 克拉玛依市| 应城市| 石林| 绍兴县| 乌拉特前旗| 高碑店市| 巴东县| 交城县| 林口县| 微山县|