来到了第十天,今天要更深入了解 struct 在 Go 里面扮演的角色,
话不多说,我们就进入正题吧 ─=≡Σ(((っ゚∀゚)っ
Structure(简称 Struct)在 Go 能让使用者透过集合不同资料打包成一个自行定义型别,而透过自定义型别生出来的资料,在物件导向的概念就可以被称作实体,甚至可以把它想像成是一个无法继承的类别。
type Cat struct {
name string
age int
}
一个 struct 可能会有零到多个栏位,每个栏位都会对应一个资料型态。
如果 struct 有多个型别相同的栏位,可以合并为一条:
type Cat struct {
name, breed string
age int
}
而要使用 struct 的方式,与宣告变数的方式一样,并且有几种的赋值方式:
map
类似,一个栏位对应一个值。type Cat struct {
name, breed string
age int
}
cat := Cat{name: "BuiBui", breed: "Mix", age: 5}
fmt.Println(cat)
type Cat struct {
name, breed string
age int
}
cat := Cat{"BuiBui", "Mix", 5}
fmt.Println(cat)
type Cat struct {
name, breed string
age int
}
cat := &Cat{"BuiBui", "Mix", 5}
fmt.Println(cat)
登愣,状况题来了!
请问 struct 内栏位的型别可以用 struct 吗?
当然可以!基本上 struct 内要放什麽资料型别都是没问题的,
来看看巢状的 struct 该怎麽应用吧:
package main
import "fmt"
type Cat struct {
name, breed string
age int
owner Ower
}
type Ower struct {
name, gender string
age int
}
func main() {
cat := Cat{
name: "BuiBui",
breed: "Mix",
age: 5,
owner: Ower{
name: "Chan",
gender: "female",
age: 18}}
fmt.Println(cat
}
只要在 ower
栏位以 Type{key: value}
形式书写就行了,是不是超简单呢!
虽然栏位配型别看起来很舒服,但其实 Go 也支援只提供型别,不写栏位的方式。
package main
import "fmt"
type Cat struct {
string
int
Ower
}
type Ower struct {
string
int
}
func main() {
cat := Cat{"BuiBui", 5, Ower{"Chan", 18}}
fmt.Println(cat)
}
struct 的文章就到今天结束,有任何问题都欢迎与我告知 :)
铁人赛文章也同时发布於 这里
<<: [Day_11]资料储存容器 - 字典(dict) & 集合(set)
>>: Day 10: Creational patterns - Singleton
Keyword: Koin 到Day20 使用Koin管理依赖注入显示在Android上 放在这边 ...
大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今天的解题Day~ 821. Shortest D...
大家好! 昨天我们建立了 insert 方法,今天我们就要延伸它的用法。 我们进入今天的主题吧! 前...
Q1. 什麽是时间型SQL 注入? Time-based sql injection 是指利用 SQ...
URI && URL URI(Uniform Resource Identifier...