struct - skynocover/Wiki-for-GoLang GitHub Wiki
struct
宣告
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{1, 2} 宣告並給值
v2 = Vertex{X: 1} Y:0 被省略
v3 = Vertex{} X:0 和 Y:0
p = &Vertex{1, 2} 类型为 *Vertex
)
method
- 使用指標進行傳值
使用return把nama()當作變數使用
go GetImg(down.name(), down.pic.URL)
func (down *page) name() string { //得到本子名稱
var name = catch(down.html, "<h1>", "<span class=")
if name != "" {
os.Mkdir(name, os.ModePerm)
return name
} else {
return ""
}
}
或是直接修改struct內的值
down.Name()
go GetImg(down.name, down.pic.URL)
func (down *page) Name() { //得到本子名稱
down.name = catch(down.name, "<h1>", "<span class=")
if down.name != "" {
os.Mkdir(name, os.ModePerm)
}
}
結構化
//點
type Point struct {
X, Y int
}
//圓
type Circle struct {
Center Point //概念類似繼承
Radius int
}
//車輪
type Wheel struct {
Circle Circle
Spokes int
}
//也可以這樣多重宣告
type Wheel struct{
Spokes int
Circle strcut{
Center point
Radius int
}
}
- 給值
var w Wheel
w.Circle.Center.X = 8
w.Circle.Center.Y = 8
w.Circle.Radius = 5
w.Spokes = 20
給值過於煩瑣
讓結構體匿名
type Circle struct {
Point
Radius int
}
type Wheel struct {
Circle
Spokes int
}
給值
var w Wheel
w.X = 8 // 等同於 w.Circle.Point.X = 8
w.Y = 8 // 等同於 w.Circle.Point.Y = 8
w.Radius = 5 // 等同於 w.Circle.Radius = 5
w.Spokes = 20
- 另一種給值
w = Wheel{
Circle: Circle{
Point: Point{X: 8, Y: 8},
Radius: 5,
},
Spokes: 20, //特別注意,最後一個成員結尾的逗點是必要的
}
//簡寫為一行
w = Wheel{Circle{Point{8, 8}, 5}, 20}
開發階段確認值
type T struct {
a int
b float64
c string
}
t := &T{ 7, -2.35, "I'm a string." }
fmt.Printf("%v\n", t)
fmt.Printf("%+v\n", t)
fmt.Printf("%#v\n", t)
- %v:單純把內容都印出來,會得到&{7 -2.35 I'm a string.}
- %+v:除了值以外,還有欄位名稱,得到&{a:7 b:-2.35 c:I'm a string.}
- %#v:可以得到最多資訊,連結構體的名稱、所在的函數都會一起印出,得到&main.T{a:7, b:-2.35, c:"I'm a string."}