capypad
0 Tage Serie
go / beginner
Snippet

Grundlegende Datentypen und Typkonvertierung

Go ist eine statisch typisierte Sprache mit expliziter Typdeklaration. Die grundlegenden Typen umfassen int für Ganzzahlen, float64 für Dezimalzahlen, bool für Wahrheitswerte und string für Text. Go erlaubt keine implizite Typkonvertierung zwischen verschiedenen Typen - du musst explizit mit der Syntax destinationType(variable) konvertieren.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main
 
import (
"fmt"
"reflect"
)
 
func main() {
var i int = 42
var f float64 = 3.14
var b bool = true
var s string = "Go"
 
fmt.Printf("int: %d, type: %s\n", i, reflect.TypeOf(i))
fmt.Printf("float: %.2f, type: %s\n", f, reflect.TypeOf(f))
fmt.Printf("bool: %t, type: %s\n", b, reflect.TypeOf(b))
fmt.Printf("string: %s, type: %s\n", s, reflect.TypeOf(s))
 
converted := float64(i)
fmt.Println("Converted int to float64:", converted)
}
Erklärung
1
var i int = 42
Integer-Variable, die ganze Zahlen enthält
2
var f float64 = 3.14
Float64-Variable, die Dezimalzahlen enthält (64-Bit-Genauigkeit)
3
var b bool = true
Boolean-Variable, die wahr oder falsch enthält
4
var s string = "Go"
String-Variable, die Textsequenzen enthält
5
float64(i)
Explizite Typkonvertierung von int nach float64 - Go erfordert explizite Casts