V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
asAnotherJack
V2EX  ›  Go 编程语言

关于 go 可变参数解包的问题

  •  
  •   asAnotherJack · 2020-12-25 16:28:17 +08:00 · 2424 次点击
    这是一个创建于 1189 天前的主题,其中的信息可能已经有所发展或是发生改变。

    rWGtw8.jpg

    如图,我想往一个接口 slice 里,append 进一个 impl slice 的所有元素,为什么单个 append 就可以,用...的方式就不行啊,这种我只能 for 循环依次 append 了吗?求大佬解惑

    type ISayHi interface {
    	Hi()
    }
    
    type SayHiImpl struct {
    
    }
    
    func (s *SayHiImpl) Hi() {
    	fmt.Println("Hi")
    }
    
    func main() {
    	s := make([]ISayHi, 0)
    	impls := make([]*SayHiImpl, 0)
    	impls = append(impls, &SayHiImpl{})
    	s = append(s, impls[0])
    	s = append(s, impls...)
    
    }
    
    9 条回复    2020-12-25 17:06:51 +08:00
    assiadamo
        1
    assiadamo  
       2020-12-25 16:31:21 +08:00
    看上去只能循环解引用加进去
    vasil
        2
    vasil  
       2020-12-25 16:33:48 +08:00
    s 和 impls 的类型不一致
    westoy
        3
    westoy  
       2020-12-25 16:42:55 +08:00
    s = append(s, s[:]...)
    gochat
        4
    gochat  
       2020-12-25 16:48:05 +08:00   ❤️ 1
    ```go
    type ISayHi interface {
    Hi()
    }

    type SayHiImpl struct {
    }

    func (s *SayHiImpl) Hi() {
    fmt.Println("Hi")
    }

    func main() {
    s := make([]ISayHi, 0)
    impls := make([]ISayHi, 0)
    impls = append(impls, &SayHiImpl{})
    s = append(s, impls[0])
    s = append(s, impls...)
    }
    ```

    这么玩
    asAnotherJack
        5
    asAnotherJack  
    OP
       2020-12-25 16:53:01 +08:00
    @gochat #4 嗯,现在就是这么搞的,就是觉得这种 单个元素能 append,slice 解包不能 append 有点反直觉,头大
    pigmen
        6
    pigmen  
       2020-12-25 16:55:49 +08:00
    mark 下不太懂,用什么单个可以,unpack 不行
    keepeye
        8
    keepeye  
       2020-12-25 16:58:46 +08:00   ❤️ 2
    简单来说,append 需要编译器支持,而编译器不支持复杂的转换。比如 []*SayHiImpl 转换成 []ISayHi 需要 O(N)的复杂度,是不支持的.
    至于单个为什么可以,因为转换单个只要 O(1)
    ZSeptember
        9
    ZSeptember  
       2020-12-25 17:06:51 +08:00   ❤️ 1
    go 不支持 Covariance 。
    append 的第二个参数是 []ISayHi,[]*SayHiImpl 并不是[]ISayHi 的子类型。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5874 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 02:16 · PVG 10:16 · LAX 19:16 · JFK 22:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.