Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang - GoMobile tool for cross platform slices of struct return type

During the journey of cross-platform mobile app development, I came across Golang which is having a GoMobile command line tool which generates language bindings that make it possible to call Go functions from Java and Objective-C. However, there are some restriction on the types used in an exported function/method as documented here: https://godoc.org/golang.org/x/mobile/cmd/gobind#hdr-Type_restrictions

So any idea about the work in progress to support slices of struct (Array of struct) in the data types used in exported functions

like image 861
saurabh Avatar asked Nov 18 '22 18:11

saurabh


1 Answers

A workaround with String as an example:

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

Usage in go:

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

On Android you can use this extension to convert it to a 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()
}
like image 138
Róbert Nagy Avatar answered May 17 '23 23:05

Róbert Nagy