mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 22:45:14 +08:00
4.5.2.5.md
This commit is contained in:
22
eBook/exercises/chapter_4/count_characters.go
Normal file
22
eBook/exercises/chapter_4/count_characters.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// count number of characters:
|
||||
str1 := "asSASA ddd dsjkdsjs dk"
|
||||
fmt.Printf("The number of bytes in string str1 is %d\n",len(str1))
|
||||
fmt.Printf("The number of characters in string str1 is %d\n",utf8.RuneCountInString(str1))
|
||||
str2 := "asSASA ddd dsjkdsjsこん dk"
|
||||
fmt.Printf("The number of bytes in string str2 is %d\n",len(str2))
|
||||
fmt.Printf("The number of characters in string str2 is %d",utf8.RuneCountInString(str2))
|
||||
}
|
||||
/* Output:
|
||||
The number of bytes in string str1 is 22
|
||||
The number of characters in string str1 is 22
|
||||
The number of bytes in string str2 is 28
|
||||
The number of characters in string str2 is 24
|
||||
*/
|
8
eBook/exercises/chapter_4/divby0.go
Normal file
8
eBook/exercises/chapter_4/divby0.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package main
|
||||
|
||||
func main() {
|
||||
a, b := 10, 0
|
||||
c := a / b // panic: runtime error: integer divide by zero
|
||||
|
||||
print(c)
|
||||
}
|
18
eBook/exercises/chapter_4/function_calls_function.go
Normal file
18
eBook/exercises/chapter_4/function_calls_function.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
var a string // global scope
|
||||
|
||||
func main() {
|
||||
a = "G"
|
||||
print(a)
|
||||
f1()
|
||||
}
|
||||
func f1() {
|
||||
a := "O" // new local variable a, only scoped within f1() !
|
||||
print(a)
|
||||
f2()
|
||||
}
|
||||
func f2() {
|
||||
print(a) // global variable is taken
|
||||
}
|
||||
// GOG
|
19
eBook/exercises/chapter_4/global_scope.go
Normal file
19
eBook/exercises/chapter_4/global_scope.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
var a = "G" // global scope
|
||||
|
||||
func main() {
|
||||
n()
|
||||
m()
|
||||
n()
|
||||
}
|
||||
|
||||
func n() {
|
||||
print(a)
|
||||
}
|
||||
|
||||
func m() {
|
||||
a = "O" // simple assignment: global a gets a new value
|
||||
print(a)
|
||||
}
|
||||
// GOO
|
17
eBook/exercises/chapter_4/local_scope.go
Normal file
17
eBook/exercises/chapter_4/local_scope.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
var a = "G" // global (package) scope
|
||||
|
||||
func main() {
|
||||
n()
|
||||
m()
|
||||
n()
|
||||
}
|
||||
func n() {
|
||||
print(a)
|
||||
}
|
||||
func m() {
|
||||
a := "O" // new local variable a is declared
|
||||
print(a)
|
||||
}
|
||||
// GOG
|
Reference in New Issue
Block a user