golang 建構函式

2021-10-06 03:37:00 字數 846 閱讀 5547

package main

import (

"fmt"

)type test struct

func newtest1(a int, b string) *test

func newtest2(a int, b string) *test

}type testconstruct func(*test)

func constructa(a int) testconstruct

}func constructb(b string) testconstruct

}func newtest3(constructs ...testconstruct) *test

return t

}func main()

// t1 := &test// too few values in test literal

t2 := newtest1(2, "3")

t3 := newtest2(3, "4")

t4 := newtest3(constructa(4), constructb("5"))

fmt.println(t1, t2, t3, t4)

}

記錄一下4種建構函式:

直接使用&struct{},大括號裡可以帶上初始化的值。如果寫了屬性,那麼初始化就不需要按照順序了;初始化的話一定要填上所有的值

使用建構函式new構造乙個變數

使用建構函式&struct構造乙個變數,&struct和new是相同的

每個屬性設定乙個賦值函式,並且返回相同的函式指標,引數是這個結構體。在初始化的時候遍歷所有的函式指標對這個結構體進行賦值

golang 建構函式

go語言的型別或結構體沒有建構函式的功能,但是我們可以使用結構體初始化的過程來模擬實現建構函式。其他程式語言建構函式的一些常見功能及特性如下 type cat struct func newcatbyname name string cat func newcatbycolor color stri...

建構函式 拷貝建構函式 賦值建構函式

class和struct很大乙個區別在於,c除了成員的訪問控制許可權,struct中的成員預設是public,而class中的field預設是private class還有乙個special的地方是它有建構函式 constructor。建構函式是class中的一員,和成員變數 其他成員函式一起構成乙...

構造函式呼叫建構函式

題目如下 問下列 的列印結果為0嗎?include stdlib.h include iostream using namespace std struct clscls int main 列印結果是不定的,不一定為0 奇怪的地方在於建構函式中呼叫了自己的另乙個建構函式 我們知道,當定義乙個物件時,...