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

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.

主站蜘蛛池模板: 江达县| 深水埗区| 仪陇县| 休宁县| 偏关县| 五莲县| 三河市| 文化| 修文县| 将乐县| 府谷县| 敦化市| 曲周县| 玉山县| 呈贡县| 武清区| 政和县| 甘泉县| 唐山市| 左权县| 东台市| 潢川县| 万盛区| 米林县| 台中市| 任丘市| 隆化县| 克什克腾旗| 新邵县| 中宁县| 剑河县| 贡山| 宁夏| 青田县| 钟祥市| 葫芦岛市| 都昌县| 龙川县| 政和县| 宜州市| 云浮市|