需求:对字符串用递归的方式进行反转,比如helloworld反转结果为dlrowolleh。代码为:

s := []byte("helloworld")
reverseString(s)
fmt.Println(string(s))

func reverseString(s []byte) {
    l := len(s)
    if l <= 1 {
        return
    } else {
        last := s[l-1]

        s = s[:l-1]
        reverseString(s)
        s = append([]byte{last}, s...)
        fmt.Println(string(s))
        fmt.Println("<<<<<<<<<")

    }
}

但是结果不符合预期:

eh
<<<<<<<<<
lhe
<<<<<<<<<
lhel
<<<<<<<<<
ohell
<<<<<<<<<
whello
<<<<<<<<<
ohellow
<<<<<<<<<
rhellowo
<<<<<<<<<
lhellowor
<<<<<<<<<
dhelloworl
<<<<<<<<<
helloworld

从最后两行可以看到,reverseString内部得到的s= dhelloworl,在调用方
那里看确是helloworld。初步原因怀疑为上一篇写到的slice作为函数参数造成的坑。然后用同样的思路,试着修改调用函数,将更改后的[]byte返回给调用方:

s := []byte("helloworld")
s = reverseString(s)
fmt.Println(string(s))//输出结果为:dlrowolleh

func reverseString(s []byte) []byte {
    l := len(s)
    if l <= 1 {
        return s
    } else {
        last := s[l-1]
        s = s[:l-1]
        s = reverseString(s)
        fmt.Println(string(s))
        s = append([]byte{last}, s...)
        //fmt.Println(string(s))
        return s
    }
}

符合预期。所以使用slice作为函数参数时一定要注意点。