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

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

Initialize a variable in the struct definition with a value

问题

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

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/dchest/uniuri"
  5. )
  6. type mail struct {
  7. url, email string
  8. uri string
  9. }
  10. func (m *mail) init() {
  11. m.uri = uniuri.NewLen(20)
  12. }
  13. func main() {
  14. m := mail{}
  15. m.init()
  16. fmt.Println(m)
  17. }

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

.\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.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/dchest/uniuri"
  5. )
  6. type mail struct {
  7. url, email string
  8. uri string = uniuri.NewLen(20)
  9. }
  10. func main() {
  11. }

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/dchest/uniuri"
  5. )
  6. type mail struct {
  7. url, email string
  8. uri string
  9. }
  10. func NewMail(url, email string) mail {
  11. uri := uniuri.NewLen(20)
  12. return mail{url, email, uri}
  13. }

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

英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/dchest/uniuri"
  5. )
  6. type mail struct {
  7. url, email string
  8. uri string
  9. }
  10. func NewMail(url, email string) mail {
  11. uri := uniuri.NewLen(20)
  12. return mail{url, email, uri}
  13. }

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:

确定