golang 為結構體新增方法

2021-10-03 10:18:23 字數 751 閱讀 2559

本節中,將會使用揹包作為「物件」,將物品放入揹包的過程作為「方法」,通過面向過程的方式和go語言中結構體的方式來理解「方法」的概念。

面向過程沒有「方法」概念,只能通過結構體和函式,由使用者使用函式引數和呼叫方式來形成接近「方法」的概念,**如下:

package main

type bag struct

func

insert

(b *bag, itemid int

)func

main()

insert() 函式將 *bag 引數放在第一位,強調 insert 會操作 *bag 結構體,但實際使用中,並不是每個人都會習慣將操作物件放在首位,一定程度上讓**失去一些正規化和描述性。同時,insert() 函式也與 bag 沒有任何歸屬概念,隨著類似 insert() 的函式越來越多,面向過程的**描述物件方法概念會越來越麻煩和難以理解。

type bag struct

func

(b *bag)

insert

(itemid int

)func

main()

每個方法只能有乙個接收器,如下圖所示

golang結構體與方法

type people inte ce type student struct func stu student speak think string talk string else return func main think speak fmt.println peo.speak think ...

Golang基礎 結構體 方法

type 結構體名稱 structtype people structvar peo people fmt.print peo 輸出 fmt.printf p peo 會列印記憶體位址值var peo people 按照結構體中屬性的順序進行賦值,可以省略屬性名稱 peo people fmt.pr...

golang結構體方法隱式呼叫

方法是golang中的乙個特性,方法可以看作是帶有特殊接受者引數的函式,最常用的是為結構體定義方法,看起來就像物件導向裡邊的物件下的方法 package main import fmt type book struct func b book setpages func b book pages 如...