V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
asAnotherJack

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

  •  
  •   asAnotherJack · Dec 25, 2020 · 3694 views
    This topic created in 1950 days ago, the information mentioned may be changed or developed.

    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 replies    2020-12-25 17:06:51 +08:00
    badbye
        1
    badbye  
       Dec 25, 2020
    看上去只能循环解引用加进去
    vasil
        2
    vasil  
       Dec 25, 2020
    s 和 impls 的类型不一致
    westoy
        3
    westoy  
       Dec 25, 2020
    s = append(s, s[:]...)
    gochat
        4
    gochat  
       Dec 25, 2020   ❤️ 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
       Dec 25, 2020
    @gochat #4 嗯,现在就是这么搞的,就是觉得这种 单个元素能 append,slice 解包不能 append 有点反直觉,头大
    pigmen
        6
    pigmen  
       Dec 25, 2020
    mark 下不太懂,用什么单个可以,unpack 不行
    keepeye
        8
    keepeye  
       Dec 25, 2020   ❤️ 2
    简单来说,append 需要编译器支持,而编译器不支持复杂的转换。比如 []*SayHiImpl 转换成 []ISayHi 需要 O(N)的复杂度,是不支持的.
    至于单个为什么可以,因为转换单个只要 O(1)
    looplj
        9
    looplj  
       Dec 25, 2020   ❤️ 1
    go 不支持 Covariance 。
    append 的第二个参数是 []ISayHi,[]*SayHiImpl 并不是[]ISayHi 的子类型。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1136 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 18:14 · PVG 02:14 · LAX 11:14 · JFK 14:14
    ♥ Do have faith in what you're doing.