How to declare to variables of different datatypes in a single statement in Go

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

How to declare to variables of different datatypes in a single statement in Go

问题

我想在Go语言中的单个语句中声明两个不同数据类型(stringerror)的变量。我不想使用短声明(:=)运算符,因为我喜欢在声明时指定变量的类型。

我正在按照Go文档中的教程进行操作。我有一个名为greetings.Hello()的函数,我正在从另一个模块中调用该函数。greetings.Hello()函数的代码如下所示:

package greetings

import (
	"errors"
	"fmt"
)

func Hello(name string) (string, error) {
	// 如果没有提供名字,返回一个带有错误信息的错误
	if name == "" {
		return "", errors.New("empty name")
	}

	// 如果收到了名字,返回一个值
	var message string = fmt.Sprintf("Welcome %v!", name)
	return message, nil
}

所以你可以看到,这个函数返回两个值(一个string和一个error)。因此,我需要在调用者中将这个函数的结果赋值给两个变量。我从名为hello的模块中调用greetings.Hello()函数。hello模块的主包的main函数如下所示:

package main

import (
	"fmt"
	"log"

	"creating_modules/greetings"
)

func main() {
	log.SetPrefix("greetings: ")
	log.SetFlags(0)

	var message string, err error = greetings.Hello("")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(message)
}

creating_modules/greetings是包含Hello()函数的greetings模块。大多数Gopher会这样处理:

message, error := greetings.Hello()

但是我想在单个语句中声明变量及其数据类型。而且这两个变量应该被赋予greetings.Hello()的返回值。上述hello模块的main函数在运行时会返回一个错误,因为赋值不正确,具体是这一行:

var message string, err error = greetings.Hello("")

当使用go run运行此代码时,Go编译器会返回以下错误:

.\hello.go:14:20: syntax error: unexpected comma at end of statement

可以通过复制粘贴上述代码来简单地复现此问题(请注意,greetings模块是一个本地模块,因此您需要使用go edit -replace设置go工具的引用路径)。

还需要注意的是,我的问题与这个问题不同,因为那个问题是关于在单个语句中声明具有相同数据类型的变量,而我的问题是关于在单个语句中声明具有不同数据类型的多个变量。

附注:我不会对Golang没有这个特性感到惊讶。

英文:

I want to declare two variables of different datatypes(string and error) in a single statement in Go. I do not want to use the short declaration(:=) operator because I like specifying the type of the variable at declaration.

I am following a Go tutorial from the Go docs. I have a function called greetings.Hello() that I am calling from another module. The greetings.Hello() function looks like this:

package greetings

import (
	"errors"
	"fmt"
)

func Hello(name string) (string, error) {
	// If no name was given, return an error with a message
	if name == "" {
		return "", errors.New("empty name")
	}

	// If a name was received, return a value
	var message string = fmt.Sprintf("Welcome %v!", name)
	return message, nil
}

So as you can see, this function returns two values(a string and an error). So ultimately, I would have to assign the result of this function to two variables in the caller. I am calling the greetings.Hello() function from a module named hello. The main function of the hello module's main package looks like this:

package main

import (
	"fmt"
	"log"

	"creating_modules/greetings"
)

func main() {
	log.SetPrefix("greetings: ")
	log.SetFlags(0)

	var message string, err error = greetings.Hello("")
	if err !=nil {
		log.Fatal(err)
	}

	fmt.Println(message)
}

The creating_modules/greetings is the greetings module that contains the function Hello(). Most of the gophers tackle it like this:

message, error := greetings.Hello()

But I want to declare the variables along with their datatypes in a single statement. Also the two variables should be assigned the return values of greetings.Hello(). The above mentioned main function of the hello module returns an error when it is run because of the incorrect assignment, referring to this line:

var message string, err error = greetings.Hello("")

The Go compiler returns this error when this code is run using go run:

.\hello.go:14:20: syntax error: unexpected comma at end of statement

This issue can simply be reproduced by copy-pasting the code above(note that the greetings module is a local module so you will need to set the reference path for go tools using go edit -replace)

Another thing to be noted is that my question is different from this question because that question is about declaring variables with the same data type in a single statement whereas mine is about declaring multiple variables with different data types in a single statement.

P.S i won't be surprised to know that Golang does not have this feature

答案1

得分: 5

在单个语句中声明变量及其数据类型是不可能的。

根据语言规范中的支持性条款变量声明

如果指定了类型,每个变量都将具有该类型。否则,每个变量将具有赋值语句中相应初始化值的类型。如果该值是无类型常量,则首先将其隐式转换为其默认类型。

因此,可以使用以下类似的方式,不指定任何类型,但你也可以使用使用:=进行短变量声明:

var message, error = greetings.Hello()

但你可以显式地声明变量及其类型信息,并使用=进行赋值。

var message string
var err error

if message, err = greetings.Hello(""); err != nil {
    log.Fatal(err)
}
英文:

> declare the variables along with their datatypes in a single statement

Not possible

Supporting clause from the language spec under Variable declarations

> If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first implicitly converted to its default type;

So something like below could work by not specifying either of the types, but you could very well use short variable declarations using := instead

var message, error = greetings.Hello()

But you can declare the variables explicitly with their type information and use the = assignment.

var message string
var err error

if message, err = greetings.Hello(""); err != nil {
    log.Fatal(err)
}

huangapple
  • 本文由 发表于 2021年11月19日 19:21:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70034059.html
匿名

发表评论

匿名网友

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

确定