The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ophunter

请教下为啥没添加进去

  •  
  •   ophunter · Dec 9, 2022 · 1638 views
    This topic created in 1255 days ago, the information mentioned may be changed or developed.
    func testMatrix(res *[][]int) {
       r := *res
       r = append(r, []int{1, 2, 3})
    }
    
    fun main(){
       res := make([][]int, 0)
       testMatrix(&res)
       fmt.Println(res)
    }
    

    这个 res 为啥是空的 []

    6 replies    2022-12-09 16:02:14 +08:00
    Mitt
        1
    Mitt  
       Dec 9, 2022
    因为 append 会生成新的 slice
    Mitt
        2
    Mitt  
       Dec 9, 2022
    正确的做法是 *res = append(*res, []int{1, 2, 3})
    ophunter
        3
    ophunter  
    OP
       Dec 9, 2022
    @Mitt 这个 append 生产的新的 slice 地址不是和原来的起始地址一样的原因是吗?
    lazydog
        4
    lazydog  
       Dec 9, 2022
    你可以打印下地址看看,就知道结果了。
    ophunter
        5
    ophunter  
    OP
       Dec 9, 2022
    @lazydog 谢谢
    ophunter
        6
    ophunter  
    OP
       Dec 9, 2022
    @Mitt 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2986 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 74ms · UTC 07:54 · PVG 15:54 · LAX 00:54 · JFK 03:54
    ♥ Do have faith in what you're doing.