相关疑难解决方法(0)

在Go中,使用结构类型的setter不能按预期工作

对结构使用setter函数,但没有按预期工作:

package main

import "fmt"

type T struct { Val string }

// this setter seems not to work
func (t T) SetVal( s string ) {
        t.Val = s
}

// this setter, using ptr to T, seems to work ok
func (t *T) SetVal2( s string ) {
        (*t).Val = s
}

func main() {
        v := T{"abc"}
        fmt.Println( v )        // prints {abc}
        v.SetVal("pdq")
        fmt.Println( v )        // prints {abc}, was expecting {pdq}!
        v.SetVal2("xyz")
        fmt.Println( v ) …
Run Code Online (Sandbox Code Playgroud)

struct go

7
推荐指数
1
解决办法
970
查看次数

标签 统计

go ×1

struct ×1