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

在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)
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题