Golang - GoMobile工具用于跨平台结构体切片返回类型

5
在跨平台移动应用程序开发的旅程中,我遇到了Golang,它具有一个GoMobile命令行工具,该工具生成语言绑定,使得可以从Java和Objective-C调用Go函数。然而,使用导出的函数/方法中使用的类型存在一些限制,如文档所述:https://godoc.org/golang.org/x/mobile/cmd/gobind#hdr-Type_restrictions
那么,对于在导出的函数中使用的数据类型支持结构体切片(数组结构)的工作进展有何想法?

我的猜测是最好在边界处使用一种序列化/反序列化步骤。 - RickyA
@RickyA 谢谢。确实,如果没有内置支持即将到来,那就是我拥有的最后选择。 - saurabh
2
这是关于此功能的gomobile项目问题:https://github.com/golang/go/issues/13445 - tmm1
2个回答

1

以下是以String为例的解决方法:

type StringCollection interface {
    Add(s string) StringCollection
    Get(i int) string
    Size() int
}

// TODO solve this with generics
type StringArray struct {
    items []string
}

func (array StringArray) Add(s string) StringArray {
    array.items = append(array.items, s)
    return array
}

func (array StringArray) Get(i int) string {
    return array.items[i]
}

func (array StringArray) Size() int {
    return len(array.items)
}

Go语言中的使用方法:

func GetExampleStringArray() *StringArray {
    strings := []string{"example1", "example2"}
    return &StringArray{items: strings}
}

在Android中,您可以使用此扩展将其转换为List<String>
fun StringArray.toStringList(): List<String> {
    val list = mutableListOf<String>()
    for (i in 0 until size()) {
        list.add(get(i))
    }
    return list
}

fun main() {
    GoPackage.getExampleStringArray().toStringList()
}

0

我认为目前没有人在处理gomobile切片接口的实现。你可能想要查看这个方便的项目。

https://github.com/scisci/go-mobile-collection

这里有一个简单的例子,展示如何在没有任何项目的情况下分享切片:

type MyType struct {
        Id       int64
        Name     string
}

var (
        items []MyType
)

func GetItemsCount() int {
        return len(items)
}

func GetItem(i int) *MyItem {
        if i >= 0 && i < len(items) {
                return &items[i]
        }
        return nil
}

在使用线程时,我通常会在代码中添加互斥锁。

我们共享业务逻辑(所有可以从移动本地代码中移出的内容),它运行得非常完美。 使用gomobile 1.13bind模式。这是iOS/Android有效跨平台开发的唯一可行解决方案。React很好,但占用更多空间。 真的很喜欢Swift,但移动应用程序中约40mb的库依赖关系使其无法承受。我们在我们的应用程序中使用它:https://play.google.com/store/apps/details?id=com.lonje和即将推出的iOS版本:https://apps.apple.com/us/app/lonje-anonymous-chat-video/id1215525783


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接