1、結構體(struct)定義:就是把使用各種資料型別定義的不同變數組合起來的高階資料型別
package main結果圖import (
"fmt")
type rect struct
func main()
fmt.println(rect2.width *rect2.lenght)
//依據結構體內變數順序賦值
rect3 := rect
fmt.println("
width:
", rect3.width, "
length:
", rect3.lenght, "
area:
", rect3.width*rect3.lenght)
}
2、結構體作為引數傳入函式,即對上面求面積封裝為函式
package main結果圖import (
"fmt")
type rect struct
func double_are(rect rect) float64
func main()
fmt.println(double_are(rect))
fmt.println("
width:
", rect.width, "
length:
", rect.length)
}
3、結構體組合函式,也就是通過限定函式呼叫者是哪個結構體,定義在結構體上面的函式叫做方法(結構體不存在內部函式)
package main結構圖import (
"fmt")
type rect struct
func (rect rect) area() float64
func main()
fmt.println("
width:
", rect.width, "
length:
", rect.length, "
area:
", rect.area())
}
4、結構體和指標,用指標來改變結構體內變數值,如果不改變結構體內變數值,方法的限定型別結構體可以不為指標型別。使用new來建立結構體指標型別
package main結果圖import (
"fmt")
type rect struct
//改變rect內引數值
func (rect *rect) double_area() float64
//不改變rect內引數值
func (rect rect) double_area2() float64
func main()
5、結構體內嵌型別,在乙個結構體內部定義另外乙個結構體型別成員
1)、has-a關係,即iphone有乙個phone
package main2)is-a關係,即iphone也是phone;假設結構體a內部定義了乙個內嵌結構體b,那麼a同時也可以呼叫所有定義在b上面的方法import (
"fmt")
type phone struct
type iphone struct
func main()
package mainfunc (phone phone) ringing()import (
"fmt")
type phone struct
type iphone struct6、介面(inte***ce):介面裡面可以定義一組方法,任何其他型別只要能夠實現了這些方法就是實現了這個介面func main()
package main7、介面還可以作為結構體成員import (
"fmt")
type phone inte***ce
type nokiaphone struct
func (nokiaphone nokiaphone) call()
func (nokiaphone nokiaphone) sendmsg()
type iphone struct
func (iphone iphone) call()
func (iphone iphone) sendmsg()
func main()
package main結果圖import (
"fmt")
type phone inte***ce
type nokiaphone struct
func (nokiaphone nokiaphone) call()
func (nokiaphone nokiaphone) sales()
inttype iphone struct
func (iphone iphone) call()
func (iphone iphone) sales()
inttype person struct
func (person person) total_cost()
int return
sum}
func main() ,
iphone,
iphone,
nokiaphone,
iphone,
}//注意phones要使用切片phones[:]
var person = person
fmt.println(person.name)
fmt.println(person.age)
fmt.println(person.total_cost())
}
和結構體 結構體型別與結構體變數
結構體 struct 是由一系列具有相同型別或不同型別的資料構成的資料集合,叫做結構體。在c語言中,結構體 struct 指的是一種資料結構,是c語言中聚合資料型別 aggregate data type 的一類。結構體可以被宣告為變數 指標或陣列等,用以實現較複雜的資料結構。結構體同時也是一些元素...
python 向C介面傳遞結構體陣列 結構體
c原始碼 1.c include include include 1.h int add int a,int b if 0 int add stus student data,int count return 1 int add stu student data int add data stude...
共用體和結構體
共用體和結構體的宣告與初始化的格式不同。宣告 struct or union new st 初始化 new st 和陣列一樣,使用逗號分隔,並用花括號括起。也可以全放在一行。可以同時完成定義結構和建立結構變數的工作,只需要將變數名放在結束括號的後面 struct or union new st ne...