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条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端