Go 如何在struct中使用带有私有变量的库
当结构中有私有变量时,我想使用氨基封送 在test2包中,test.go:Go 如何在struct中使用带有私有变量的库,go,private,Go,Private,当结构中有私有变量时,我想使用氨基封送 在test2包中,test.go: type Lnt struct { Neg bool abs string // this variable } func NewLnt() Lnt { return Lnt{ Neg: true, abs: "abcdefef", } } func TestAbc(t *testing.T) { s := test2.NewLnt()
type Lnt struct {
Neg bool
abs string // this variable
}
func NewLnt() Lnt {
return Lnt{
Neg: true,
abs: "abcdefef",
}
}
func TestAbc(t *testing.T) {
s := test2.NewLnt()
t.Log("s=", s)
cdc := amino.NewCodec()
b, err := cdc.MarshalBinary(s)
assert.Nil(t, err)
t.Log("b=",b)
var s2 test2.Lnt
err = cdc.UnmarshalBinary(b, &s2)
assert.Nil(t, err)
assert.Equal(t, s, s2)
t.Log("s2=", s2)
}
encoding_test.go:39: s= {true abcdefef}
encoding_test.go:55:
Error Trace: encoding_test.go:55
Error: Not equal:
expected: test2.Lnt{Neg:true, abs:"abcdefef"}
actual : test2.Lnt{Neg:true, abs:""} // error
Diff:
--- Expected
+++ Actual
@@ -2,3 +2,3 @@
Neg: (bool) true,
- abs: (string) (len=8) "abcdefef"
+ abs: (string) ""
}
Test: TestAbc
encoding_test.go:57: s2= {true }
测试go文件:
type Lnt struct {
Neg bool
abs string // this variable
}
func NewLnt() Lnt {
return Lnt{
Neg: true,
abs: "abcdefef",
}
}
func TestAbc(t *testing.T) {
s := test2.NewLnt()
t.Log("s=", s)
cdc := amino.NewCodec()
b, err := cdc.MarshalBinary(s)
assert.Nil(t, err)
t.Log("b=",b)
var s2 test2.Lnt
err = cdc.UnmarshalBinary(b, &s2)
assert.Nil(t, err)
assert.Equal(t, s, s2)
t.Log("s2=", s2)
}
encoding_test.go:39: s= {true abcdefef}
encoding_test.go:55:
Error Trace: encoding_test.go:55
Error: Not equal:
expected: test2.Lnt{Neg:true, abs:"abcdefef"}
actual : test2.Lnt{Neg:true, abs:""} // error
Diff:
--- Expected
+++ Actual
@@ -2,3 +2,3 @@
Neg: (bool) true,
- abs: (string) (len=8) "abcdefef"
+ abs: (string) ""
}
Test: TestAbc
encoding_test.go:57: s2= {true }
结果:
type Lnt struct {
Neg bool
abs string // this variable
}
func NewLnt() Lnt {
return Lnt{
Neg: true,
abs: "abcdefef",
}
}
func TestAbc(t *testing.T) {
s := test2.NewLnt()
t.Log("s=", s)
cdc := amino.NewCodec()
b, err := cdc.MarshalBinary(s)
assert.Nil(t, err)
t.Log("b=",b)
var s2 test2.Lnt
err = cdc.UnmarshalBinary(b, &s2)
assert.Nil(t, err)
assert.Equal(t, s, s2)
t.Log("s2=", s2)
}
encoding_test.go:39: s= {true abcdefef}
encoding_test.go:55:
Error Trace: encoding_test.go:55
Error: Not equal:
expected: test2.Lnt{Neg:true, abs:"abcdefef"}
actual : test2.Lnt{Neg:true, abs:""} // error
Diff:
--- Expected
+++ Actual
@@ -2,3 +2,3 @@
Neg: (bool) true,
- abs: (string) (len=8) "abcdefef"
+ abs: (string) ""
}
Test: TestAbc
encoding_test.go:57: s2= {true }
私有变量“abs”丢失
它不受支持,或者在这种情况下有其他方法使用它吗?简单的回答是您不能 这里发生的事情是,您正在将所有导出的值编组为二进制格式,但未报告的值不包括在内,因为编组程序无权访问它们 二进制数据被解组到一个新的结构中,因为未报告的字段不在二进制数据中,所以结构不可能用该值初始化。(此外,它不能设置值,因为它未报告)
如果您希望此测试通过,或者接受数据编组时丢失,则需要导出结构字段(公开)。简而言之,您不能 这里发生的事情是,您正在将所有导出的值编组为二进制格式,但未报告的值不包括在内,因为编组程序无权访问它们 二进制数据被解组到一个新的结构中,因为未报告的字段不在二进制数据中,所以结构不可能用该值初始化。(此外,它不能设置值,因为它未报告)
如果您希望此测试通过,或接受数据编组时丢失的事实,则需要导出结构字段(公开)。非常感谢