- Hands-On Full Stack Development with Go
- Mina Andrawos
- 251字
- 2021-07-02 12:33:31
Struct
A struct in Go is a data structure that is composed of fields, where each field has a type. Here is what a Go struct looks like:
type myStruct struct{
intField int
stringField string
sliceField []int
}
The preceding code creates a struct type that is called myStruct, which contains three fields:
- intField of type int
- stringField of type string
- sliceField of type []int
You can then initialize and use that struct type in your code:
var s = myStruct{
intField: 3,
stringField: "three",
sliceField : []int{1,2,3},
}
The preceding method of initialization is also known as struct literals. There is a shorter version of it that looks like this:
var s = myStruct{3,"three",[]int{1,2,3}}
You can also use what is known as dot notation, which looks as follows:
var s = myStruct{}
s.intField = 3
s.stringField = "three"
s.sliceField= []int{1,2,3}
You can obtain a pointer to a struct by doing this:
var sPtr = &myStruct{
intField:3,
stringField:"three",
sliceField: []int{1,2,3},
}
A dot notation can be used with a Go struct pointer, since Go will understand what needs to be done without the need to do any pointer de-referencing:
var s = &myStruct{}
s.intField = 3
s.stringField = "three"
s.sliceField= []int{1,2,3}
If the Go struct field names start with lower case letters, they will not be visible to external packages. If you want your struct or its fields to be visible to other packages, start the struct and/or field name with upper case letters.
Now, let's talk about Go methods.
- 觸·心:DT時代的大數據精準營銷
- PostgreSQL Cookbook
- Learning Elixir
- Mastering Swift 2
- Python Web數據分析可視化:基于Django框架的開發實戰
- Learning Laravel's Eloquent
- 青少年信息學競賽
- Visual Basic程序設計上機實驗教程
- OpenCV 4計算機視覺項目實戰(原書第2版)
- 編程可以很簡單
- Natural Language Processing with Python Quick Start Guide
- Learning VMware vSphere
- Spring Boot從入門到實戰
- Joomla!Search Engine Optimization
- 優化驅動的設計方法