Security with Go
上QQ阅读APP看书,第一时间看更新

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.