我在一个包含私有字段的结构中有一个结构:
package foo
type Foo struct {
x int
y *Foo
}
Run Code Online (Sandbox Code Playgroud)
另一个包(例如,白盒测试包)需要访问它们:
package bar
import "../foo"
func change_foo(f *Foo) {
f.y = nil
}
Run Code Online (Sandbox Code Playgroud)
有没有办法声明bar是一种"朋友"包或任何其他方式,以便能够访问其foo.Foo私人成员bar,但仍然保持私有所有其他包(可能是某些东西unsafe)?
我想复制数据结构的实例。由于 go 没有任何内置函数,因此我使用第三方库:https://github.com/emirpasic/gods。
例如,我可能会尝试使用带有哈希集的深复制。
var c, d hashset.Set
c = *hashset.New()
c.Add(1)
deepcopy.Copy(d, c)
c.Add(2)
fmt.Println(c.Contains(2))
fmt.Println(d.Contains(2))
fmt.Println(c.Contains(1))
fmt.Println(d.Contains(1))
Run Code Online (Sandbox Code Playgroud)
然而,哈希集的内容根本没有被复制。我知道深层复制模块无法复制未导出的值,但是由于库中没有内置的“复制构造函数”,这是否意味着无法在不修改其代码的情况下使用库完全复制数据结构实例?(我研究过的其他一些库也出现类似的问题)。
我是 golang 新手,感觉不对,因为类似的事情可以很容易地实现,例如在 C++ 中。我知道我可以编写自己的版本或修改他们的代码,但这比预期的工作量太多,这就是为什么我认为应该有一种惯用的方法。
PS:对于那些可能会说“不需要这样的功能”的人,我将一些具有某些数据结构的复杂状态分配给并行计算线程,他们直接使用状态并且不能互相干扰。
Go 编程语言的标准库公开了一个名为 的结构strings.Builder,它允许通过重复连接以有效的方式轻松构建字符串,类似于 C# 或 Java 的StringBuilder.
在 Java 中,我会使用StringBuilder的构造函数来“克隆”对象,如下所示:
StringBuilder newBuffer = new StringBuilder(oldBuffer.toString());
Run Code Online (Sandbox Code Playgroud)
在Go中,我只能看到以下两行方式:
newBuffer := strings.Builder{}
newBuffer.WriteString(oldBuffer.String())
Run Code Online (Sandbox Code Playgroud)
没有其他.Clone()初始化方法(我可能还没有找到)。
是否有另一种方法比我提出的方法更简短/简洁?
我知道,有人问过类似的问题,但我没有找到这种情况的答案:
type ExportedStruct struct{ //comes from a dependency, so I can't change it
unexportedResource ExportedType
}
Run Code Online (Sandbox Code Playgroud)
我想打电话给一个出口的方法Close()上unexportedResource。
我所做的是:
rs := reflect.ValueOf(myExportedStructPtr).Elem() //myExportedStructPtr is a pointer to an ExportedStruct object
resourceField := rs.FieldByName("unexportedResource")
closeMethod := resourceField.MethodByName("Close")
closeMethod.Call([]reflect.Value{reflect.ValueOf(context.Background())})
Run Code Online (Sandbox Code Playgroud)
,这导致reflect.flag.mustBeExported using value obtained using unexported field。
这很烦人,因为我想运行多个利用 的测试ExportedStruct,但只要不使用底层资源,我就不能。
因为我可以访问私有字段(如解释在这里)我有一点希望,我被允许访问该场莫名其妙的公共方法,太。也许我只是反映错误?
我目前正在使用反射从结构中获取字段并将值作为接口值的一部分返回。我遇到了未导出字段的问题,我希望能够获取未导出的值并将它们与导出的字段一起返回。当我尝试从未导出的字段中获取值时,出现以下错误:
reflect.Value.Interface:无法返回从未导出的字段或方法中获得的值 [已恢复]
我一直在使用https://github.com/fatih/structs作为我的代码的基础,并希望它能够处理未导出的字段。
// Values returns us the structs values ready to be converted into our repeatable digest.
func (s *StructWrapper) Values() []interface{} {
fields := s.structFields()
var t []interface{}
for _, field := range fields {
val := s.value.FieldByName(field.Name)
if IsStruct(val.Interface()) {
// look out for embedded structs, and convert them to a
// []interface{} to be added to the final values slice
t = append(t, Values(val.Interface())...)
} else {
t = append(t, val.Interface())
}
} …Run Code Online (Sandbox Code Playgroud)