如何在struct方法中设置和获取字段 [英] How to set and get fields in struct's method

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

问题描述

在创建这样的结构后:

type Foo struct {
    name string
}

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

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

如何创建Foo的新实例并设置并获取名称? 我尝试了以下方法:

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?

工作场所

推荐答案

注释(且有效)示例:

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.

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

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