Skip to content

[勘误]反馈一个第2章第2.2节的示例运行结果错误 #101

Description

@ocaraworks

问题描述
slice原理一节的2.2示例的运行结果和解释错误。

如何找到这个错误

  • 章节:2.2 题目二
  • 页码:

您认为应该如何?
false

图片
如果有可能,尽量提供图片。

其他补充信息

示例的源代码:

package main

import (
"fmt"
)

func AddElement(slice []int, e int) []int {
return append(slice, e)
}

func main() {
var slice []int
slice = append(slice, 1, 2, 3)

newSlice := AddElement(slice, 4)
fmt.Println(&slice[0] == &newSlice[0])

}

错误原因:
因为AddElement函数内部append重新扩容了,但是它和原来的slice是两个内存地址值。

注:我的golang 1.16.7版本

Activity

  1. ocaraworks commented on Dec 21, 2021

    @ocaraworks
    Author

    这个错误。请运行核查。

  2. RainbowMango commented on Dec 21, 2021

    @RainbowMango
    Owner

    题目二?
    是这个吗?

    下面函数输出什么?
    ```go
    func SliceRise(s []int) {
    	s = append(s, 0)
    	for i := range s {
    		s[i]++
    	}
    }
    
    func SlicePrint() {
    	s1 := []int{1, 2}
    	s2 := s1
    	s2 = append(s2, 3)
    	SliceRise(s1)
    	SliceRise(s2)
    	fmt.Println(s1, s2)
    }
    

    单选:

    • A: [2, 3] [2, 3, 4]
    • B: [1, 2] [1, 2, 3]
    • C: [1, 2] [2, 3, 4]
    • D: [2, 3, 1] [2, 3, 4, 1]
    
    PS: 不知道你看的是第几次印刷的版本,有点对照不上。
    
  3. RainbowMango commented on Dec 21, 2021

    @RainbowMango
    Owner

    感谢描述的是这个问题 #88

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions