多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### **go如何用两个协程交替打印出123456** ~~~ 协程1打印基数,协程2打印偶数,用一个channel实现 //打印奇数 func PrintOddNumber(ch chan int, num int) { defer wg.Done() for i := 0; i <= num; i++ { ch <- i if i%2 != 0 { fmt.Println("奇数:", i) } } } //打印偶数 func PrintEvenNumber(ch chan int, num int) { defer wg.Done() for i := 1; i <= num; i++ { <-ch if i%2 == 0 { fmt.Println("偶数:", i) } } } var wg sync.WaitGroup func main() { ch := make(chan int) wg.Add(1) go PrintOddNumber(ch, 10) go PrintEvenNumber(ch, 10) wg.Wait() } ~~~ ### **使用go语言将数组中12300045变成12345000** ``` func MobileNnm(arr []int) []int { arr2 := make([]int, 0) oneCount := 0 for _, v := range arr { if v == 0 { oneCount++ } else { arr2 = append(arr2, v) } } for i := 0; i < oneCount; i++ { arr2 = append(arr2, 0) } return arr2 } func main() { //使用go语言将12300045变成12345000 val1 := []int{1, 2, 3, 0, 0, 0, 4, 5} val2 := MobileNnm(val1) fmt.Println(val2) } 结果:[1 2 3 4 5 0 0 0] ```