Golang 如何向函数传递一个slice

Golang 如何向函数传递一个slice

Slice是一个可变长度的序列,用来存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。它就像一个有索引值和长度的数组一样,但分片的大小是可以调整的,它们不像数组那样有固定的大小。在Go语言中,你可以将一个分片传递给一个函数,这意味着函数会得到分片的副本。

分片是通过值传递给函数的,同时还有分片的容量和长度,分片的指针总是指向底层数组。因此,如果我们对通过值传递给函数的分片做了一些改变,就会反映在函数外的分片上。让我们借助于一个例子来讨论这个概念。

例1 :

// Go program to illustrate how to
// pass a slice to the function
package main
  
import "fmt"
  
// Function in which slice
// is passed by value
func myfun(element []string) {
  
    // Modifying the given slice
    element[2] = "Java"
    fmt.Println("Modified slice: ", element)
}
  
// Main function
func main() {
  
    // Creating slice
    slc := []string{"C#", "Python", "C", "Perl"}
      
    fmt.Println("Initial slice: ", slc)
  
    // Passing the slice to the function
    myfun(slc)
      
    fmt.Println("Final slice:", slc)
  
}

输出

Initial slice:  [C# Python C Perl]
Modified slice:  [C# Python Java Perl]
Final slice: [C# Python Java Perl]

解释: 在上述例子中,我们有一个名为slc的分片。这个片断被传递到myfun()函数中。我们知道,即使在一个函数中传递,分片指针总是指向同一个引用。因此,当我们将C值改为Java的索引值2时。这个改变也反映了函数外的分片,所以修改后的最终分片是 [C# Python Java perl]

例2 :

// Go program to illustrate how to
// pass a slice to the function
package main
  
import "fmt"
  
// Function in which slice
// is passed by value
func myfun(element []string) {
  
    // Here we only modify the slice
    // Using append function
    // Here, this function only modifies
    // the copy of the slice present in 
    // the function not the original slice
    element = append(element, "Java")
    fmt.Println("Modified slice: ", element)
}
  
// Main function
func main() {
  
    // Creating a slice
    slc := []string{"C#", "Python", "C", "Perl"}
      
    fmt.Println("Initial slice: ", slc)
  
    // Passing the slice
    // to the function
      
    myfun(slc)
    fmt.Println("Final slice: ", slc)
  
}

输出

Initial slice:  [C# Python C Perl]
Modified slice:  [C# Python C Perl Java]
Final slice:  [C# Python C Perl]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程