结构体内引用函数,则该函数的运行过程令人难以理解
1. 运行环境
go 1.17
2. 问题描述?
package main
import (
"fmt"
"log"
)
type ConChan struct {
ItemChan chan interface{}
}
func main() {
e := &ConChan{
ItemChan: ItemSave(),
}
e.ConRun(1,2,3,4,5)
}
func ItemSave() chan interface{} {
out := make(chan interface{})
go func() {
for {
item := <-out
log.Printf("%s", item)
fmt.Println(item)
}
}()
return out
}
func (e *ConChan) ConRun(seeds ...int) {
for _, i := range seeds {
go func(i int) {
e.ItemChan <- i
}(i)
}
}
问题一、这段代码,在ConChan结构体中的ItemChan在main中被初始化为ItemSave(),即return out,
在e.ConRun()时会往e.ItemChan 即out中写数据。我不理解这里为什么会触发ItemSave()中的log.Printf(“%s”, item),是每写一次就触发一次函数吗?
问题二、这段代码运行无结果,问题出在哪?
3. 您期望得到的结果?
将传入的 e.ConRun(1,2,3,4,5)打印出来。
4. 您实际得到的结果?
无运行结果,也无错误信息。