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

  • Security with Go
  • John Daniel Leon
  • 238字
  • 2021-06-30 19:06:47

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.

主站蜘蛛池模板: 龙州县| 宜阳县| 香格里拉县| 南华县| 恭城| 湟源县| 合江县| 蓬莱市| 繁峙县| 合水县| 安阳市| 若尔盖县| 沙洋县| 临清市| 阿合奇县| 娄底市| 江华| 虞城县| 丰原市| 石城县| 清涧县| 潞西市| 江城| 嘉祥县| 聂荣县| 钟山县| 申扎县| 个旧市| 库尔勒市| 南和县| 宁阳县| 东乡| 托克托县| 宁津县| 绥化市| 靖江市| 云和县| 乐清市| 大兴区| 伊通| 当雄县|