在[for]循环中处理返回值

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

Working with returned value in [for] loop

问题

我有使用C#的经验,可以处理用户的命令,代码如下:

string command;
while ((command = GetCommandFromUser()) != EXIT_COMMAND)
    ProcessCommand(command);

这段简单的代码允许我从用户那里获取命令(从控制台或类似的地方),并对其进行处理。

但是在Go语言中,我只有以下代码:

var command string
for command = GetCommandFromUser(); command != ExitCommand; command = GetCommandFromUser() {
    ProcessCommand(command)
}

我能简化它吗?

英文:

I have an experience with C#, where I can work with commands from user like this:

string command;
while ( (command = GetCommandFromUser()) != EXIT_COMMAND )
    ProcessCommand(command);

This simple code allows me get command from user (from Console or something like this) and process it.

But in Go I have only this code:

var command string
for command = GetCommandFromUser(); command != ExitCommand; command = GetCommandFromUser() {
	ProcessCommand(command)
}

Can I do it simply?

答案1

得分: 2

for {
    command := GetCommandFromUser()
    if command == ExitCommand {
        break
    }

    ProcessCommand(command)
}
for {
    command := GetCommandFromUser()
    if command == ExitCommand {
        break
    }

    ProcessCommand(command)
}
for {
    command := GetCommandFromUser()
    if command == ExitCommand {
        break
    }

    ProcessCommand(command)
}
英文:
for {
    command := GetCommandFromUser()
    if command == ExitCommand {
        break
    }

    ProcessCommand(command)
}

huangapple
  • 本文由 发表于 2017年7月13日 16:11:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/45074998.html
匿名

发表评论

匿名网友

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

确定