发表更新2 分钟读完 (大约327个字)
golang常考的go语言笔试题
计算两个和再打印输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package main
import ( "fmt" "sync" )
func sum(a, b int) int { var res int for i := a; i <= b; i++ { res += i } return res }
func main() { var sum1, sum2 int var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done() sum1 = sum(1, 100) }()
go func() { defer wg.Done() sum2 = sum(101, 200) }()
wg.Wait()
res := sum1 + sum2 fmt.Println(res) }
|
打印输出字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package main
import ( "fmt" "strings" "sync" "time" )
func main() { var wg sync.WaitGroup wg.Add(2) str := "hello,world!" str1 := []byte(str) sc := make(chan byte, len(str)) count := make(chan int) for _, v := range str1 { sc <- v } close(sc)
go func() { defer wg.Done() for { ball, ok := <-count if ok { pri, ok1 := <-sc if ok1 { fmt.Printf("go 2 : %c\n", pri) } else { close(count) return } count <- ball } else { return } } }()
go func() { defer wg.Done() for { time.Sleep(8 * time.Millisecond) ball, ok := <-count if ok { pri, ok1 := <-sc if ok1 { fmt.Printf("go 1 : %c\n", pri) } else { close(count) return } } else { return } count <- ball } }()
count <- 23 wg.Wait() }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package main
import ( "fmt" )
func printString(str string, done chan bool) { for _, letter := range str { fmt.Printf("%c", letter) } done <- true }
func main() { done := make(chan bool)
go printString("Hello", done) <-done
go printString("World", done) <-done }
|
N个协程交替打印1-100
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package main
import ( "fmt" "sync" )
func printer(wg *sync.WaitGroup, ch chan int) { defer wg.Done() for num := range ch { fmt.Println(num) ch <- num + 1 } }
func main() { numGoroutines := 5
var wg sync.WaitGroup wg.Add(numGoroutines)
ch := make(chan int)
for i := 0; i < numGoroutines; i++ { go printer(&wg, ch) }
ch <- 1
wg.Wait() close(ch) }
|