douzhulan1815
2016-08-02 22:27
浏览 506
已采纳

在golang中按引用传递数组

I am from a C background and passing an array in C style causes an error.

package main
import "fmt"

func f(a *int){
  fmt.Println(a[1])
}

func main(){
  var a [100]int
  a[1]=100
  f(a)
}

Error:: cannot use a (type [100]int) as type *int in argument to f

图片转代码服务由CSDN问答提供 功能建议

我来自C背景,以C样式传递数组会导致错误。 \ n

 包main 
import“ fmt” 
 
func f(a * int){
 fmt.Println(a [1])
} 
 
func main(){
 var  [100] int 
a [1] = 100 
f(a)
} 
   
 
 

错误 :: 在f 的参数中不能使用(类型[100] int)作为* int类型

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dty47696 2016-08-03 01:07
    已采纳

    As others have mentioned in comments, you probably want to use a slice rather than an array. Slices are passed by reference already, so no need to specify pointers. The make statement below creates a slice of ints (backed by an array). In the code below, I gave it a length of 2 and a capacity of 100 in order to satisfy your goal of assigning to index 1.

    import (
        "fmt"
    )
    
    func f(a []int) {
        fmt.Println(a[1])
    }
    
    func main() {
        a := make([]int, 2, 100)
        a[1] = 100
        f(a)
    }
    
    打赏 评论
  • douxi3432 2016-08-03 02:00

    you must use a slice instead of an array as argument of function. for example:

    func p(a int){
    fmt.Println(a)
    }
    func main() {
        var a = make([]int,2,10) //2 is length, 10 is capacity
        a[0] = 10
        p(a[0])
    }
    

    array is value type, slice is reference type. you can see more at https://blog.golang.org/go-slices-usage-and-internals

    Wish it help you!

    打赏 评论

相关推荐 更多相似问题