在Android中,如何正确地计算0从Go函数返回的值?
以下是我尝试过的:
// ExportedGoFunction returns a pointer to a GoStruct or nil in case of fail
func ExportedGoFunction() *GoStruct {
return nil
}然后我使用以下方法生成一个.aar文件:
gomobile bind -v --target=android
在我的Java代码中,我试图将nil计算为空,但它不起作用。Java代码:
GoLibrary.GoStruct goStruct = GoLibrary.ExportedGoFunction();
if (goStruct != null) {
// This block should not be executed, but it is
Log.d("GoLog", "goStruct is not null");
}免责声明: go库工作中的其他方法完美无缺
发布于 2015-09-21 01:14:06
作为将来可能的参考,从09/2015开始,我想出了两种解决这个问题的方法。
第一种方法是从Go代码和尝试/捕捉返回一个错误-- Java中的错误。下面是一个例子:
// ExportedGoFunction returns a pointer to a GoStruct or nil in case of fail
func ExportedGoFunction() (*GoStruct, error) {
result := myUnexportedGoStruct()
if result == nil {
return nil, errors.New("Error: GoStruct is Nil")
}
return result, nil
}然后尝试/捕获Java中的错误
try {
GoLibrary.GoStruct myStruct = GoLibrary.ExportedGoFunction();
}
catch (Exception e) {
e.printStackTrace(); // myStruct is nil
}这种方法都是惯用的Go和Java,但是即使它能够防止程序崩溃,它也会用try/catch语句使代码膨胀,造成更多的开销。
因此,基于用户@SnoProblem回答了解决它的非惯用方法,并正确地处理了我想出的空值:
// NullGoStruct returns false if value is nil or true otherwise
func NullGoStruct(value *GoStruct) bool {
return (value == nil)
}然后检查中的代码如下:
GoLibrary.GoStruct value = GoLibrary.ExportedGoFunction();
if (GoLibrary.NullGoStruct(value)) {
// This block is executed only if value has nil value in Go
Log.d("GoLog", "value is null");
}发布于 2015-09-18 00:52:31
查看go mobile的测试包,您似乎需要将空值转换为该类型。
来自SeqTest.java文件:
public void testNilErr() throws Exception {
Testpkg.Err(null); // returns nil, no exception
}编辑:也是一个毫无例外的例子:
byte[] got = Testpkg.BytesAppend(null, null);
assertEquals("Bytes(null+null) should match", (byte[])null, got);
got = Testpkg.BytesAppend(new byte[0], new byte[0]);
assertEquals("Bytes(empty+empty) should match", (byte[])null, got);它可能很简单,如:
GoLibrary.GoStruct goStruct = GoLibrary.ExportedGoFunction();
if (goStruct != (GoLibrary.GoStruct)null) {
// This block should not be executed, but it is
Log.d("GoLog", "goStruct is not null");
}编辑:实用方法的建议:
您可以向库中添加一个实用程序函数,为您提供类型化的nil值。
func NullVal() *GoStruct {
return nil
}虽然有点麻烦,但它的开销应该比多包装器和异常处理少。
https://stackoverflow.com/questions/32636972
复制相似问题