int和C.int在Go语言中有什么区别?

huangapple go评论70阅读模式
英文:

What's the difference between int and C.int in go?

问题

以下是翻译好的内容:

import "C"

func f() {
  var vGo int
  var vC  C.int
  // 编译错误:
  // 无法将 &vGo (类型 *int) 作为参数传递给类型为 *C.int 的函数...
  C.c_function(&vGo)  
  // 编译通过:
  C.c_function(&vC)
}

我使用 CGO_ENABLED=1 GOARCH=arm 进行编译...

在这种情况下int  C.int 类型有什么区别
在哪里可以找到关于在 Go 中使用 C 类型的额外信息

希望对你有帮助!如果你有其他问题,请随时提问。

英文:
import "C"

func f() {
  var vGo int
  var vC  C.int
  // fails to compile with error
  // cannot use &vGo (type *int) as type *C.int in argument to...
  C.c_function(&vGo)  
  // compiles just fine:
  C.c_function(&vC)
}

I compile with CGO_ENABLED=1 GOARCH=arm...

What's the different in int and C.int types in this case?
Where do I find additional information on C types in GO?

答案1

得分: 2

类型之间有什么区别?这取决于情况。如果你使用的是64位系统,Go的int类型将是64位,而C的int类型将是32位。如果你使用的是32位系统,它们之间没有实质性的区别。

在哪里可以找到关于Go中C类型的更多信息?可以查看C的文档。正如评论中提到的,Go不允许隐式的数值类型转换,所以需要进行显式的转换。

英文:

What's the difference between the types? It depends. If you're on 64bit, the Go int will be 64 bits while the C int will be 32. If you're on 32bit, there is no real difference.

Where do I find additional information on C types in Go? Look at documentation for C. As mentioned in the comments, implicit numeric type conversions aren't allowed in Go so a conversion is required.

答案2

得分: 1

Go语言有意地不支持隐式类型转换,但也有一些例外情况1

  • 在以下情况下,值x可以赋值给类型为T的变量("x可以赋值给T"):
    • x的类型与T相同。
    • x的类型V和T具有相同的底层类型,并且V或T中至少有一个不是命名类型。
    • T是一个接口类型,并且x实现了T。
    • x是一个双向通道值,T是一个通道类型,x的类型V和T具有相同的元素类型,并且V或T中至少有一个不是命名类型。
    • x是预声明的标识符nil,T是指针、函数、切片、映射、通道或接口类型。
    • x是一个可以用类型T的值表示的无类型常量。

在你的情况下,类型转换是为了匹配可能不同的内存布局2

英文:

Go deliberately does not support implicit type conversion, with some exceptions1:

> A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
>
> * x's type is identical to T.
> * x's type V and T have identical underlying types and at least one of V or T is not a named type.
> * T is an interface type and x implements T.
> * x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
> * x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
> * x is an untyped constant representable by a value of type T.

The conversion in your case is needed to match potentially different memory layouts2.

huangapple
  • 本文由 发表于 2016年4月8日 00:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/36482444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定