如何设置和获取Golang结构中的字段? [英] how to set and get fields in Golang structs?

查看:237
本文介绍了如何设置和获取Golang结构中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个像这样的结构:

  type Foo struct {
name string


func(f Foo)SetName(name string){
f.name = name
}

func(f Foo)GetName string(){
return f.name
}

如何创建一个新的实例Foo并设置并获取名称?
我试过以下内容:

  p:= new(Foo)
p.SetName(Abc )
name:= p.GetName()
fmt.Println(name)

没有打印,因为名称是空的。那么如何在结构体中设置和获取一个字段?

解析方法

b
$ b

 包主

导入fmt

类型Foo结构{
名称字符串
}

SetName接收到一个指向Foo的指针,以便修改它。
func(f * Foo)SetName(name string){
f.name = name
}

//名字收到Foo的副本,因为它没有'不需要修改它。
func(f Foo)Name()string {
return f.name
}

func main(){
//注意Foo { }。新的(Foo)只是一个用于& Foo {}
//的语法糖,我们不需要指向Foo的指针,所以我替换了它。
//然而,与问题无关。
p:= Foo {}
p.SetName(Abc)
name:= p.Name()
fmt.Println(name)
}

测试并采用 Go Tour of Go 了解更多关于方法和指针的知识,以及基础知识根本就是Go。


After creating a struct like this:

type Foo struct {
   name string        

}
func (f Foo) SetName(name string){
    f.name=name
}

func (f Foo) GetName string (){
   return f.name
}

How do I create a new instance of Foo and set and get the name? I tried the following:

p:=new(Foo)
p.SetName("Abc")
name:=p.GetName()
fmt.Println(name)

Nothing gets printed, because name is empty. So how do I set and get a field inside a struct?

解决方案

Commentary (and working) example:

package main

import "fmt"

type Foo struct {
    name string
}

// SetName receives a pointer to Foo so it can modify it.
func (f *Foo) SetName(name string) {
    f.name = name
}

// Name receives a copy of Foo since it doesn't need to modify it.
func (f Foo) Name() string {
    return f.name
}

func main() {
    // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{}
    // and we don't need a pointer to the Foo, so I replaced it.
    // Not relevant to the problem, though.
    p := Foo{}
    p.SetName("Abc")
    name := p.Name()
    fmt.Println(name)
}

Test it and take A Tour of Go to learn more about methods and pointers, and the basics of Go at all.

这篇关于如何设置和获取Golang结构中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆