drui0508 2019-06-20 02:41
浏览 50
已采纳

编写对泛型类型进行操作的方法的惯用方式

What's the idiomatic way to write a method that operates on a "generic" array?

I have a typed array:

a := make([]int, 0)

I want to write a simple method that could operate on an array of any type:

func reverse(a []interface{}) []interface{} {
    for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
        a[i], a[j] = a[j], a[i]
    }
    return a
}

Using this method a = reverse(a) gives me 2 errors:

cannot use a (type []int) as type []interface {} in argument to reverse
cannot use reverse(a) (type []interface {}) as type []int in assignment
  • 写回答

1条回答 默认 最新

  • douzhang1852 2019-06-20 07:27
    关注

    Until generics arrive (which will most likely be called contracts), reflection and interfaces are the only tools to achieve such generalization.

    You could define reverse() to take a value of interface{} and use the reflect package to index it and swap elements. This is usually slow, and harder to read / maintain.

    Interfaces provide a nicer way but requires you to write methods to different types. Take a look at the sort package, specifically the sort.Sort() function:

    func Sort(data Interface)
    

    Where sort.Interface is:

    type Interface interface {
            // Len is the number of elements in the collection.
            Len() int
            // Less reports whether the element with
            // index i should sort before the element with index j.
            Less(i, j int) bool
            // Swap swaps the elements with indexes i and j.
            Swap(i, j int)
    }
    

    sort.Sort() is able to sort any slices that implement sort.Interface, any slices that have the methods the sorting algorithm needs to do its work. The good thing about this approach is that you can sort other data structures too not just slices (e.g. a linked list or an array), but usually slices are used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应