C data types
- Go course
- Advanced
- Lesson 15/68
- 4 min
Learn types like C.int and C.char.
C data types
C types appear in Go with names like C.int, C.long, C.double, C.char. They are not the same as Go's int or float64; an explicit conversion is required.
var a C.int = 5
b := int(a) * 2 // C.int → int
c := C.double(1.5) // float64 → C.doubleSizes can vary by platform: C.long is 8 bytes on Linux and 4 on Windows.
Structs and enums
A C struct nokta is used in Go as C.struct_nokta; you access its fields directly. enum constants also come through as C.NAME.
/*
struct nokta { int x; int y; };
*/
import "C"
var p C.struct_nokta
p.x = 3Practice Type conversion
In the preamble define double yarim(double x) { return x / 2; }. Convert v := 9.0 to C.double, pass it to the function, convert the result to float64 and print it.
Starter code
package main
/*
// C kodu buraya
*/
import "C"
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
/*
double yarim(double x) { return x / 2; }
*/
import "C"
import "fmt"
func main() {
v := 9.0
r := float64(C.yarim(C.double(v)))
fmt.Println(r)
}Expected output
4.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If a C function returns <code>double</code>, how do you get a <code>float64</code> in Go?
- C.float64(C.f())
- float64(C.f()) Correct answer
- C.f().(float64)
- No conversion is needed
Explanation: C.double is a separate type; to use it in Go you convert it explicitly with float64(...).
2 Convert to a C type
x := 10
r := C.kare(C.____(x))
x := 10
r := C.kare(C.int(x))
Explanation: A Go int is converted to C.int before passing it to a C function.
3 C and Go types
| Term | Meaning |
|---|---|
C.int |
int32 sized |
C.double |
float64 counterpart |
C.char |
One byte |
C.struct_nokta |
A C struct |