1.go的基本数据类型有
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128
package main
import (
"fmt"
"math/cmplx"
"math"
)
// int default 0
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
const (
Big = 1 << 100
Small = Big >> 99
)
type Point struct {
X int
Y int
}
// change bigger
func needInt(x int) int {
return x*10 + 1
}
// change smaller
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
// parameters can be used as varaibles
fmt.Print("5+3 and 5-3 return : ")
fmt.Println(xySumSub(5,3))
// data type
const f = "type:%T, value:%v\n"
fmt.Printf(f, ToBe, ToBe)
fmt.Printf(f, MaxInt, MaxInt)
fmt.Printf(f, z, z)
// truncate pi to intefer:
pi := math.Pi
fmt.Println(int(pi),int(pi+0.5),float32(3),math.Sqrt(1.414))
fmt.Println(pi)
// An untyped constant takes the type needed by its context.
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
// math
fmt.Println("2^3",math.Pow(2,3))
fmt.Println("10%%3, 10/3",10%3,10/3) // this is the same as c language
// struct : most grammer is the same as c language
point := Point{1,2}
q := &point
point.X = 10
moveLeft(point,1)
moveRight(q,100)
q.Y = 0
fmt.Println("point:",point)
newPoint := new(Point)
fmt.Println(newPoint)
// array slice
p := []int{2, 3, 5, 7, 11, 13}
fmt.Println("p ==", p)
fmt.Println("p[1:4] ==", p[1:4])
// missing low index implies 0
fmt.Println("p[:3] ==", p[:3])
// missing high index implies len(s)
fmt.Println("p[4:] ==", p[4:])
// attention: array has length and capacity
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
arrayT := new([2][4]int)
arrayT[0][1] = 3
arrayT[1][1] = 5
fmt.Println("length of arrayT : ",len(arrayT))
fmt.Println("length of arrayT[0] : ", len(arrayT[0]))
for _,v := range arrayT {
for j := range v {
fmt.Printf("%d ",v[j])
}
fmt.Println()
}
arrayT2 := make([][]int,3,6) // create the first layer of the array
for i := 0; i < 3; i++ {
arrayT2[i] = make([]int,5,5)// create the second layer of the array
}
for i:=0; i<3; i++ {
for j:=0; j<5; j++ {
fmt.Print(arrayT2[i][j]," ")
}
fmt.Println()
}
}
func xySumSub(x,y int) (sum, sub int){
sum = x + y
sub = x - y
return
}
func moveLeft(point Point,step int) {
point.X -= step
}
func moveRight(point *Point,step int) {
point.X += step
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
4379

被折叠的 条评论
为什么被折叠?



