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

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

Working with returned value in [for] loop

问题

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

  1. string command;
  2. while ((command = GetCommandFromUser()) != EXIT_COMMAND)
  3. ProcessCommand(command);

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

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

  1. var command string
  2. for command = GetCommandFromUser(); command != ExitCommand; command = GetCommandFromUser() {
  3. ProcessCommand(command)
  4. }

我能简化它吗?

英文:

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

  1. string command;
  2. while ( (command = GetCommandFromUser()) != EXIT_COMMAND )
  3. 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:

  1. var command string
  2. for command = GetCommandFromUser(); command != ExitCommand; command = GetCommandFromUser() {
  3. ProcessCommand(command)
  4. }

Can I do it simply?

答案1

得分: 2

  1. for {
  2. command := GetCommandFromUser()
  3. if command == ExitCommand {
  4. break
  5. }
  6. ProcessCommand(command)
  7. }
  1. for {
  2. command := GetCommandFromUser()
  3. if command == ExitCommand {
  4. break
  5. }
  6. ProcessCommand(command)
  7. }
  1. for {
  2. command := GetCommandFromUser()
  3. if command == ExitCommand {
  4. break
  5. }
  6. ProcessCommand(command)
  7. }
英文:
  1. for {
  2. command := GetCommandFromUser()
  3. if command == ExitCommand {
  4. break
  5. }
  6. ProcessCommand(command)
  7. }

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:

确定