You make the attribute privately so it cannot be accessed from the outside package.
For the same package access, you can't. The philosophy of Golang is: you are the owner of the code, so you can do anything you want.
However, if you want to make the field immutable, you can wrap again one data type in a struct named ImmutableSomething
and stored in the different packages. For example:
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}
}
Then you can use that:
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)
}