结构体的初始化函数

huangapple go评论94阅读模式
英文:

init function for structs

问题

我意识到Go语言没有类,而是推崇结构体的概念。

结构体是否有类似于类的构造函数的初始化函数?

示例:

type Console struct {
    X int
    Y int
}

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

// 这里我想要运行我的初始化函数
var console Console

// 或者在这里如果我使用
var console Console = new(Console)
英文:

I realize that Go does not have classes but pushes the idea of structs instead.

Do structs have any sort of initialization function that can be called similar to a __construct() function of a class?

Example:

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)

答案1

得分: 67

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}
英文:

Go doesn't have implicit constructors. You would likely write something like this.

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)
}

Output:

{5 0}

答案2

得分: 7

Go没有自动构造函数。通常你需要创建自己的NewT() *T函数来执行必要的初始化操作。但是它必须手动调用。

英文:

Go does not have automatic constructors. Typically you create your own NewT() *T function which performs the necessary initialization. But it has to be called manually.

答案3

得分: 0

这是一个Go结构体的初始化示例:

type Console struct {
    X int
    Y int
}

// 常规用法,创建一个函数以便于创建对象
func NewConsole(x, y int) *Console {
    return &Console{X: x, Y: y}
}

// "手动"创建对象(指针版本与非'&'版本相同)
consoleP := &Console{X: 1, Y: 2}
console := Console{X: 1, Y: 2}

// 内联初始化
consoleInline := struct {
	X int
	Y int
}{
	X: 1,
	Y: 2,
}
英文:

This is a Go struct initialize complete:

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,
}

huangapple
  • 本文由 发表于 2011年11月29日 07:36:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/8303939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定