Go 防止修改结构数据成员的惯用方法

Go 防止修改结构数据成员的惯用方法,go,Go,一些谷歌搜索的结论如下: 1) Go不支持不可变/常量数据成员。 2) Go不支持私有数据成员。相反,使用包隔离数据是惯用的做法 那么,防止对结构的数据成员进行后期修改的惯用方法是什么 例如,我想声明一个线程池并一次性决定它的大小 type ThreadPool struct { tp_size int } func (tp* ThreadPool) Init(size int) { tp.tp_size = size; // Allocate space... } 您将

一些谷歌搜索的结论如下: 1) Go不支持不可变/常量数据成员。 2) Go不支持私有数据成员。相反,使用包隔离数据是惯用的做法

那么,防止对结构的数据成员进行后期修改的惯用方法是什么

例如,我想声明一个线程池并一次性决定它的大小

type ThreadPool struct {
    tp_size int  
}

func (tp* ThreadPool) Init(size int) {
  tp.tp_size = size;
  // Allocate space...
}

您将属性设置为私有,因此无法从外部包访问该属性

对于相同的包访问,您不能。Golang的理念是:你是代码的所有者,所以你可以做任何你想做的事情

但是,如果要使字段不可变,可以在名为
ImmutableSomething
的结构中再次包装一种数据类型,并将其存储在不同的包中。例如:

package util

type ImmutableInt struct {
    val int
}

func NewImmutableInt(val int) ImmutableInt {
    return ImmutableInt{val: val}
}

func (i ImmutableInt) Get() int {
    return i.val
}

func (i ImmutableInt) Set(val int) ImmutableInt {
    return ImmutableInt{val: val}
}
然后你可以使用它:

package app

import "util"

type ThreadPool struct {
    size util.ImmutableInt
}

func NewThreadPool(size int) ThreadPool {
    return ThreadPool{size: util.NewImmutableInt(size)}
}

func test() {
    pool := NewThreadPool(10)

    // you cannot do this because ImmutableInt is in another package
    pool.size.val = 3

    // this  won't work
    pool.size.Set(3)

    // but you can do this. which is weird. 
    // and praying when someone does this, they know something not right
    pool.size = util.NewImmutableInt(3)
}

ImmutableInt{size}
util
包之外的编译时错误,请参阅和。@icza是的,您是对的。我刚修好。谢谢。将int包装在结构中(然后包装中)是有意义的。谢谢