38

Goにはクラスがありませんが、代わりに構造体のアイデアを推進していることに気付きました。

構造体には、クラスの __construct() 関数と同様に呼び出すことができる初期化関数がありますか?

例:

type Console struct {
    X int
    Y int
}

func (c *Console) init() {
    c.X = "5"
}

// Here I want my init function to run
var console Console

// or here if I used
var console Console = new(Console)
4

3 に答える 3

64

Goには暗黙のコンストラクターはありません。あなたはおそらくこのようなものを書くでしょう。

package main

import "fmt"

type Console struct {
    X int
    Y int
}

func NewConsole() *Console {
    return &Console{X: 5}
}

var console Console = *NewConsole()

func main() {
    fmt.Println(console)
}

出力:

{5 0}
于 2011-11-29T01:04:52.237 に答える
6

Go には自動コンストラクタがありません。通常NewT() *T、必要な初期化を実行する独自の関数を作成します。ただし、手動で呼び出す必要があります。

于 2011-11-29T00:58:38.360 に答える
0

これは Go 構造体の初期化完了です:

type Console struct {
    X int
    Y int
}

// Regular use case, create a function for easy create.
func NewConsole(x, y int) *Console {
    return &Console{X: x, Y: y}
}

// "Manually" create the object (Pointer version is same as non '&' version)
consoleP := &Console{X: 1, Y: 2}
console := Console{X: 1, Y: 2}

// Inline init
consoleInline :=  struct {
    X int
    Y int
}{
    X: 1,
    Y: 2,
}

于 2019-07-12T16:19:58.250 に答える