猿问

golang怎么像python一样把逻辑写在函数外面?跪求!

在python中可以这样写如文件内容:
fob=open('./file.txt','a')
defwrite(string):
fob.write(string)
defmain():
foriinmessages:
write(i)
fob.close()
在golang中怎么把fob写到函数外面?下面只是举的一个普通例子,我知道可以把varlogfile和write函数写到main函数中,但是,如果其它函数要调用write函数怎么办?
packagemain
import(
"fmt"
...
)
//↓这样写不行,应该怎么做?让这个文件内的函数能使用logfile变量
varlogfile,err=os.OpenFile("./test.txt",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0666)
iferr!=nil{
fmt.Println("openfilefail")
}
funcmain(){
for_,v:=rangemessages{
write(v)
}
logfile.Close()
}
funcwrite(msgstring){
logfile.WriteString(msg)
}
撒科打诨
浏览 305回答 2
2回答

慕仙森

大概这样吧packagemainimport("fmt"...)varlogfilefilefuncinit(){logfile,err=os.OpenFile("./test.txt",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0666)iferr!=nil{fmt.Println("openfilefail")}}funcmain(){for_,v:=rangemessages{write(v)}logfile.Close()}funcwrite(msgstring){logfile.WriteString(msg)}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答