- 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.
- 普林斯頓微積分讀本(修訂版)
- Introduction to Blockchain and Ethereum
- 奧妙的數(shù)學(xué)問答
- Origin 9.0科技繪圖與數(shù)據(jù)分析超級學(xué)習(xí)手冊
- 魔方的思維世界
- 幾何之美
- 越玩越聰明的印度數(shù)學(xué)和孫子算經(jīng)
- 高等數(shù)學(xué)同步練習(xí)指導(dǎo)
- Hands-On Blockchain with Hyperledger
- 數(shù)字、代數(shù)和圖象(全彩版)
- 代數(shù)的歷史:人類對未知量的不舍追蹤(修訂版)
- 數(shù)學(xué)建模
- 非線性回歸分析與SAS智能化實現(xiàn)
- 歐幾里得之窗
- 奇妙的數(shù)學(xué):激發(fā)大腦潛能的經(jīng)典名題(升級版)