Go语言入门
Go 语言是一门简单有效的编程语言,可以轻松实现并发、内存安全,并且有很好的性能。以下是一些 Go 语言的入门代码示例:
- 打印 "Hello, World!"
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
- 变量声明和赋值
package main
import "fmt"
func main() {
var a int = 10
var b int = 20
var c int
c = a + b
fmt.Println("Value of c is", c)
}
- 数据类型
package main
import "fmt"
func main() {
var a int = 10
var b float32 = 20.3
var c string = "Hello, World!"
var d bool = true
fmt.Printf("a: %v\n", a)
fmt.Printf("b: %v\n", b)
fmt.Printf("c: %v\n", c)
fmt.Printf("d: %v\n", d)
}
- 运算符
package main
import "fmt"
func main() {
a := 10
b := 20
fmt.Println("Addition:", a+b)
fmt.Println("Subtraction:", a-b)
fmt.Println("Multiplication:", a*b)
fmt.Println("Division:", a/b)
fmt.Println("Modulus:", a%b)
}
- 控制流程 - 条件语句
package main
import "fmt"
func main() {
a := 10
if a > 5 {
fmt.Println("a is greater than 5")
} else {
fmt.Println("a is not greater than 5")
}
}
- 控制流程 - 循环
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
fmt.Println("Counter:", i)
}
}
- 函数
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
x := 10
y := 20
sum := add(x, y)
fmt.Println("Sum:", sum)
}
- 指针
package main
import "fmt"
func swap(a *int, b *int) {
var temp int
temp = *a
*a = *b
*b = temp
}
func main() {
x := 10
y := 20
swap(&x, &y)
fmt.Println("x:", x)
fmt.Println("y:", y)
}
- 数组
package main
import "fmt"
func main() {
var arr [5]int
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50
for i := 0; i < 5; i++ {
fmt.Println("Element at", i, "is", arr[i])
}
}
- Slice (切片)
package main
import "fmt"
func main() {
var numbers []int
numbers = append(numbers, 10)
numbers = append(numbers, 20)
numbers = append(numbers, 30)
for i, x := range numbers {
评论已关闭