drp935159 2017-03-25 16:23
浏览 8
已采纳

函数是否可以更改在其他地方声明的字符串数组的大小? golang

I would like to remove an element from the slice in place. But when I do this I end up producing two empty elements in the underlying array. I already searched here, here

package main

import "fmt"

//String remove adjacent duplicates from a string array
func rmDup(str []string) []string {
    for i := 1; i < len(str); i++ {
        if str[i] == str[i-1] {
            copy(str[i:], str[i+1:])
            str[len(str)-1] = ""
            str = str[:len(str)-1]
        }
    }
    return str
}

func main() {

    str := []string{"dog", "cat", "cat", "mouse", "mouse", "zebra", "zebra"}

    fmt.Println(str)
    newstr := rmDup(str)
    fmt.Println(str)
    fmt.Println(newstr)
    fmt.Println(len(str), cap(str), "final")
    fmt.Println(len(newstr), cap(newstr), "final")
}

Is there any way that str in main can return the size and capacity defined in rmDup()

  • 写回答

2条回答 默认 最新

  • dsv768456 2017-03-25 18:53
    关注

    It turned out that I was able to find the answer myself. Since the Go language performs function calls by value it is impossible to change a slice declared in another scope, except using pointers.

    package main
    
    import "fmt"
    
    //String remove adjacent duplicates from a string array
    func rmDup(str *[]string) []string {
     var s = *str
     for i := 1; i < len(s); i++ {
        if s[i] == s[i-1] {
            copy(s[i:], s[i+1:])
            s[len(s)-1] = ""
            s = s[:len(s)-1]
        }
    }
    *str = s
    return s
    }
    
    func main() {
    
      str := []string{"dog", "cat", "cat", "mouse", "mouse", "zebra", 
      "zebra"}
    
      fmt.Println(str)
      newstr := rmDup(&str)
      fmt.Println(str)
      fmt.Println(newstr)
      fmt.Println(len(str), cap(str), "final")
      fmt.Println(len(newstr), cap(newstr), "final")
    }
    

    Output:

    [dog cat cat mouse mouse zebra zebra]
    [dog cat mouse zebra]
    [dog cat mouse zebra]
    4 7 final
    4 7 final
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法