从 gomobile bind 评估 nil 值

Evaluate nil values from gomobile bind

评估 nil 从 Android Java 中的 Go 函数返回的值的正确方法是什么?

这是我尝试过的方法:

// ExportedGoFunction returns a pointer to a GoStruct or nil in case of fail
func ExportedGoFunction() *GoStruct {
  return nil
}

然后我使用 gomobile 生成一个 .aar 文件:

gomobile bind -v --target=android

在我的 Java 代码中,我试图将 nil 计算为 null 但它不起作用。 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 库中的其他方法完美无缺

查看了go mobile的测试包,貌似需要将null值强制转换为类型。

来自 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
}

仍然有点 hacky,但它应该比多个包装器和异常处理的开销更少。

为了将来可能的参考,截至 09/2015,我想出了两种处理问题的方法。

第一个是 return 来自 Go 代码的错误和 try/catch-ing 中的错误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
}

然后try/catch错误在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) 
}

然后检查 Java 中的代码,例如:

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");
}