在结构定义中初始化一个变量的值。

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

Initialize a variable in the struct definition with a value

问题

如何在结构体中初始化属性的值。看一下代码片段,我尝试像这样做。

package main

import (
	"fmt"
	"github.com/dchest/uniuri"
)

type mail struct {
	url, email string
	uri        string
}

func (m *mail) init() {
	m.uri = uniuri.NewLen(20)
}

func main() {
	m := mail{}
	m.init()
	fmt.Println(m)
}

但是我得到了编译器错误。

.\assign_default_struct.go:10: syntax error: unexpected =, expecting }

有没有一种方法可以在结构体中初始化变量的值?

英文:

How I can initialize a property in the struct with a value. Look at code snippet, I try like this.

package main

import (
	"fmt"
	"github.com/dchest/uniuri"
)

type mail struct {
	url, email string
	uri string = uniuri.NewLen(20)
}


func main() {

	
}

But I've got compiler error.

> .\assign_default_struct.go:10: syntax error: unexpected =, expecting }

Is there a way, to initialize variable in the struct with a value?

答案1

得分: 1

这样做的最佳方式是创建一个构造函数,如下所示:

package main

import (
    "fmt"
    "github.com/dchest/uniuri"
)

type mail struct {
    url, email string
    uri        string
}

func NewMail(url, email string) mail {
    uri := uniuri.NewLen(20)
    return mail{url, email, uri}
}

请注意,这是一个Go语言的代码示例,用于创建一个名为mail的结构体,并定义了一个名为NewMail的构造函数。构造函数接受urlemail作为参数,并使用uniuri包生成一个长度为20的随机字符串作为uri字段的值。最后,构造函数返回一个初始化后的mail结构体实例。

英文:

The best way to do this would be to make a constructor as such:

package main

import (
    "fmt"
    "github.com/dchest/uniuri"
)

type mail struct {
    url, email string
    uri string
}


func NewMail(url, email string) mail {
    uri := uniuri.NewLen(20)
    return mail{url, email, uri}
}

huangapple
  • 本文由 发表于 2014年8月14日 18:27:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/25305828.html
匿名

发表评论

匿名网友

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

确定