“sep”在《The Go Programming Language》一书中的echo程序中有什么作用?

huangapple go评论76阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;os&quot;
)

func main() {
	var s, sep string
	for i := 1; i &lt; len(os.Args); i++ {
		s += sep + os.Args[i]
		sep = &quot; &quot;
	}
	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

huangapple
  • 本文由 发表于 2015年11月9日 07:21:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33600221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定