downloadbooks_2014 2018-01-17 19:56
浏览 26
已采纳

我可以在切片中内联声明接口列表吗?

package main

import (
    "fmt"
)

func main() {
    var a A
    var b B

    for _, v := range []WhatAreYou{a, b} {
        fmt.Println(v.Question())
    }
}

type WhatAreYou interface {
    Question() string
}

type A struct {
    string
}

type B struct {
    int
}

func (a A) Question() string {
    return "I'm an A"
}

func (b B) Question() string {
    return "I'm a B"
}

The code above works as I expect and calls the function on each interface as expected. Go Play

In my actual code I intend to have many different types implementing an interface. How can I get rid of the var a A var b B etc and simply declare them all in the slice? i.e. I tried and failed with the following and other variations

for _, v := range []WhatAreYou{a A, b B} {
  • 写回答

1条回答 默认 最新

  • dqknycyt92288 2018-01-18 09:46
    关注

    []WhatAreYou{A{}, B{}}

    This is correct, thanks to mkopriva. Composite Literals

    Now I understand a little better what I am doing here I think I understand why this question is down voted too. The question doesn't really make sense. I was so hung up on the idea of the interface I didn't think of anything else. var a A is declaring a struct that happens to implement an interface. This is even more obvious if you initialise the struct e.g. var a = A{"hello"} or inline A{"hello"}, B{2}

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog