加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang append()受fmt.Println()影响的奇怪行为

发布时间:2020-12-16 09:25:49 所属栏目:大数据 来源:网络整理
导读:我注意到Golang的append()有一些奇怪的行为.我理解切片容量如何影响新的底层数组是否被分配的基本概念,但为什么我是否使用fmt.Println()后附加已经影响了追加的结果? package mainimport "fmt"func main() { a := []byte("AAA") b := append(a,[]byte("BBB"
我注意到Golang的append()有一些奇怪的行为.我理解切片容量如何影响新的底层数组是否被分配的基本概念,但为什么我是否使用fmt.Println()后附加已经影响了追加的结果?

package main

import "fmt"

func main() {
    a := []byte("AAA")

    b := append(a,[]byte("BBB")...)
    fmt.Println(" a: ",string(a)," b: ",string(b))

    c := append(a,[]byte("CCC")...)
    fmt.Println(" a: ",string(b)," c: ",string(c))

    fmt.Println(&b) //try commenting this out and in and running the program
}

链接到此处运行代码:https://play.golang.org/p/jJ-5ZxTBIn

解决方法

你是对的:
那是因为 The Go Playground版旧(go1.6.2),使用新版本.

正确的输出(使用go版本go1.7rc6)是:

a:  AAA  b:  AAABBB
 a:  AAA  b:  AAACCC  c:  AAACCC

1- The Go Playground(go1.6.2):

package main

import "fmt"

func main() {
    a := make([]byte,100,1000)
    a = []byte("AAA")

    b := append(a,string(c))

    //fmt.Println(&b) //try commenting this out and in and running the program
}

输出:

a:  AAA  b:  AAABBB
 a:  AAA  b:  AAABBB  c:  AAACCC

2- Go Playground(go1.6.2):

package main

import "fmt"

func main() {
    a := make([]byte,string(c))

    fmt.Println(&b) //try commenting this out and in and running the program
}

输出:

a:  AAA  b:  AAABBB
 a:  AAA  b:  AAACCC  c:  AAACCC
&[65 65 65 67 67 67]

使用go版本go1.7rc6:

package main

import "fmt"

func main() {
    a := make([]byte,string(c))

    //fmt.Println(&b) //try commenting this out and in and running the program
}

输出:

a:  AAA  b:  AAABBB
 a:  AAA  b:  AAACCC  c:  AAACCC

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读