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

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.

主站蜘蛛池模板: 克拉玛依市| 洞口县| 定陶县| 浙江省| 巴南区| 瑞丽市| 永寿县| 云和县| 彭山县| 元朗区| 分宜县| 金阳县| 营口市| 镇江市| 山丹县| 伊春市| 会同县| 丰顺县| 彝良县| 比如县| 新龙县| 城固县| 武邑县| 本溪市| 鸡东县| 将乐县| 旌德县| 忻州市| 施甸县| 漳平市| 英吉沙县| 景宁| 盐池县| 昭觉县| 汪清县| 广灵县| 淳化县| 光泽县| 剑河县| 登封市| 峨边|