dongwu3747 2013-08-06 07:47
浏览 29
已采纳

如何在Go中为内置类型创建别名的文字切片

I have some golang code that manipulates slices of an interface type (Comparable). To test my code, I want to create some fake data and operate on it. However, I'm having trouble doing this in a way that is not incredibly tedious. The only thing I can think to do is create a new type for testing (in this case an alias of type int) that satisfies the Comparable interface, and then feed my tests literal slices of that type. I envision it looking something like the following:

type Comparable interface {
    LT(Comparable) bool
    AsFloat() float64
} 

type testInt int 

func (self testInt) LT(other Comparable) bool { 
    return float64(self) < other.AsFloat() 
} 

func (self testInt) AsFloat() float64 { 
    return float64(self) 
} 

func TestAFunction(t *testing.T) { 
    FunctionToTest([]Comparable{7, 4, 2, 1})
    ....
}

However, with this example, the compiler will complain that type int cannot be used as a Comparable. I understand why this is happening, but I'm not sure how to solve it. First, I don't know how to create a literal of type testInt. Second, I have to write a significant number of these functions. Working with literal ints is far more convenient for my purposes.

Is there a way to work with type aliases of builtin types such that the compiler can correctly infer the correct type of literals with a minimum of code?

Additionally, is there perhaps a better way to accomplish what I am trying to do, i.e., generate hard data that satisfies an interface for use in testing?

  • 写回答

3条回答 默认 最新

  • donglv6747 2013-08-06 14:44
    关注

    There are a number of ways to accomplish this. The problem, as you correctly state, is that the Go compiler cannot automatically convert int to Comparable (since doing so would require finding all possible equivalent types, and figuring out which of those equivalent types satisfy the Comparable interface, and then if there are more than one... you get the idea). Thus, you'll have to do one of two things:

    Write an explicit type conversion:

    FunctionToTest([]Comparable{ testInt(7), testInt(4), testInt(2), testInt(1) })
    

    However, if you need a lot of literals, this could get really annoying. Thus, you could also:

    Write a function to convert []int to []Comparable:

    func intToComparable(i []int) []Comparable {
        c := make([]Comparable, len(i))
        for i, v := range i {
            c[i] = testInt(v)
        }
        return c
    }
    

    and then you'd only have to do:

    FunctionToTest(intToComparable([]int{ 7, 4, 2, 1 }))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi