首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从gomobile计算零值

从gomobile计算零值
EN

Stack Overflow用户
提问于 2015-09-17 17:57:58
回答 2查看 538关注 0票数 2

在Android中,如何正确地计算0Go函数返回的值?

以下是我尝试过的:

代码语言:javascript
复制
// 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代码:

代码语言:javascript
复制
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库工作中的其他方法完美无缺

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-21 01:14:06

作为将来可能的参考,从09/2015开始,我想出了两种解决这个问题的方法。

第一种方法是从Go代码和尝试/捕捉返回一个错误-- Java中的错误。下面是一个例子:

代码语言:javascript
复制
// 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中的错误

代码语言:javascript
复制
try {
   GoLibrary.GoStruct myStruct = GoLibrary.ExportedGoFunction();
} 
catch (Exception e) {
   e.printStackTrace(); // myStruct is nil   
}

这种方法都是惯用的GoJava,但是即使它能够防止程序崩溃,它也会用try/catch语句使代码膨胀,造成更多的开销。

因此,基于用户@SnoProblem回答了解决它的非惯用方法,并正确地处理了我想出的空值:

代码语言:javascript
复制
// NullGoStruct returns false if value is nil or true otherwise
func NullGoStruct(value *GoStruct) bool {
    return (value == nil) 
}

然后检查中的代码如下:

代码语言:javascript
复制
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");
}
票数 2
EN

Stack Overflow用户

发布于 2015-09-18 00:52:31

查看go mobile的测试包,您似乎需要将空值转换为该类型。

来自SeqTest.java文件:

代码语言:javascript
复制
 public void testNilErr() throws Exception {
    Testpkg.Err(null); // returns nil, no exception
  }

编辑:也是一个毫无例外的例子:

代码语言:javascript
复制
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);

它可能很简单,如:

代码语言:javascript
复制
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值。

代码语言:javascript
复制
func NullVal() *GoStruct {
    return nil
}

虽然有点麻烦,但它的开销应该比多包装器和异常处理少。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32636972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档