英文:
What's the point of "sep" in echo program in The Go Programming Language book?
问题
这是《Go语言程序设计》一书中的echo程序。它基本上会在你运行程序后,将你在控制台输入的内容原样输出。
sep
字符串变量的作用是什么?
实际上,即使不使用sep
变量进行字符串拼接,该程序也可以正常运行。
可以使用s += os.Args[i]
代替s += sep + os.Args[i]
。
英文:
Source: https://github.com/adonovan/gopl.io/blob/master/ch1/echo1/main.go
<!-- language: go -->
package main
import (
"fmt"
"os"
)
func main() {
var s, sep string
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
Here is the echo program from the The Go Programming Language book. It basically echoes whatever you type in the console after you run the program.
What is the point of sep
string variable?
The program seems to run perfectly fine without and concatinating this way.
s += os.Args[i]
instead of s += sep + os.Args[i]
答案1
得分: 3
sep 确保单词之间有空格,而不是在开头或结尾。
这就是为什么它是一个变量。
英文:
sep makes sure that there is a space between words and not at the beginning or end.
That's why it's a variable
答案2
得分: 1
在命令行(终端或CMD.exe)中,使用cd
命令切换到包含此文件的文件夹,并执行以下命令:
go run main.go a b c
输出结果将为:
> a b c
然后,从代码中删除sep
变量,并再次从命令行运行它。新的输出结果将为:
>abc
因此,sep
变量被用作分隔符,它在应用程序启动时在主函数中的两个命令行参数之间添加了空格。
英文:
In command line (Terminal or CMD.exe), cd
to folder with this file and execute:
go run main.go a b c
Output will be:
> a b c
Then, remove the sep
variable from code and run it from command line again. New output will be:
>abc
Therefore,sep
variable is used as separator - it adds blank space between two command line arguments passed to main function on application startup
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论