1.实现a^b次方
package main func main() {
r2 := power1(2,4)
println(r2)
}
func power1(a uint64, b uint64) (r uint64) { //a是底数,b是幂,返回r
var i uint64
var temp uint64
if a != 0{
temp = 1
for i=1;i<=b;i++{
temp = temp * a
}
return temp
}
return //这里return只是占一个位置,不然会报错,实际不返回任何值;并且这个函数在调用时候,只能接收一个值,否则会报错
}
2.接收两个参数,返回两个数值
package main func main() {
t1, t2 := test(10,20)
println(t1)
println(t2)
} func test(a int, b int)(r1 int, r2 int) {
return a + b, a - b
}
3.转义字符练习
package main import "fmt" func main() {
fmt.Println("test\n") //换行符
fmt.Println("test\\n") //使用转义字符,打印\n;
fmt.Println("test\rttt") //遇到\r的时候,换行打印后面内容
fmt.Println("test\ttt") //空一格tab键的长度,打印后面内容
fmt.Println("test\vtt") //空格长度是\t的一半
}
C:/Users/Adong/Adong.exe [C:/Users/Adong]
test test\n
test
ttt
test tt
test tt
4.常量和变量
package main import "fmt" func main() {
const a int = 0
const b string = "hello!!!"
a = 2 //如果编译的话,这个地方会出错,因为给常量重新赋值了
fmt.Println(a)
fmt.Println(b)
}
C:/Go/bin/go.exe build -i [C:/Users/Adong]
# _/C_/Users/Adong
.\test.go:8:4: cannot assign to a
错误: 进程退出代码 2.
package main import "fmt" func main() {
const a int = 0
const b string = "hello!!!"
var c uint
c = 1
c = 2 //变量可以重新赋值,以最新的赋值为准
//a = 2 //如果编译的话,这个地方会出错,因为给常量重新赋值了
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
再举一个简单例子:
package main import "fmt" func main() {
const (
a = 0
b = 1
c = 2
)
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
C:/Go/bin/go.exe build -i [C:/Users/Adong]
成功: 进程退出代码 0.
C:/Users/Adong/Adong.exe [C:/Users/Adong]
0
1
2
成功: 进程退出代码 0.
常量如果不赋值:
package main import "fmt" func main() {
const (
a = 0
b = 1
c = 2
d
)
fmt.Println(a, b, c, d)
} // 执行结果:
0 1 2 2
package main import "fmt" func main() {
const (
i = iota //0
a //1
b = "heh"
c = "heh"
d = iota
e
)
fmt.Println(a, b, c, d, e)
}
iota的使用(可以给常量计数,出现一个常量的时候,会自增1,遇到const关键字后,自动变为0)
package main import "fmt" func main() {
const (
i = iota //0
a //1
b = "heh"
c = "heh"
d = iota
e
)
fmt.Println(a, b, c, d, e)
} //执行结果:
1 heh heh 4 5