Home > OS >  Declare mutiple variables on the same line with types in Go
Declare mutiple variables on the same line with types in Go

Time:10-12

I have the below code snippet:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    var reader *bufio.Reader = bufio.NewReader(os.Stdin)
    fmt.Println("Enter your name")
    name, err := reader.ReadString('\n') //THIS LINE
    if err == nil {
        fmt.Println("Hello "   name)
    }
}

My question is, if I want to NOT use the := syntax (like I have at the first line of main()), how would I rewrite the ReadString() invocation with types?

I tried the following, with the corresponding errors:

  1. var name string, err error = reader.ReadString('\n') -> syntax error: unexpected comma at end of statement
  2. var name, err string, error = reader.ReadString('\n') -> syntax error: unexpected comma at end of statement
  3. Taking a hint from Multiple variables of different types in one line in Go (without short variable declaration syntax) I also tried var (name string, err error) = reader.ReadString('\n') which also gives the same error.

For the above linked question, the marked answer simply suggests using two lines for two different variable types. But how would that work for the return values of a function like ReadString()?

CodePudding user response:

First of all,

name, err := reader.ReadString('\n')`

is perfectly fine. Most IDE's will display you the types of the return values of ReadString() if you would not know them.

As the linked answer details, a variable declaration can have one optional type at most, so specifying 2 types is not possible.

If it bothers you that the types are not visible, that means readability is more important to you. If it is, break with that "one-liners-for-the-win" philosophy.

If you want the types to be visible in the source code, declare the types prior, and use assignment:

var (
    name string
    err  error
)
name, err = reader.ReadString('\n')

If you still need a one liner (just for fun), it requires a helper function. The name of the helper function can "state" the expected types:

func stringAndError(s string, err error) (string, error) {
    return s, err
}

Then you can use either a variable declaration or a short variable declaration:

var name, err = stringAndError(reader.ReadString('\n'))
// OR
name, err := stringAndError(reader.ReadString('\n'))
  •  Tags:  
  • go
  • Related