英文:
cannot define variable in function - Go
问题
我对这个看似简单的任务遇到了一些麻烦。
我有一个函数,它将一个包含小时和分钟值的结构体格式化为字符串。
type Clock struct {
h int
m int
}
func (c *Clock) String() string {
h string
m string
if c.m < 10 {
m := fmt.Sprintf("0%d", c.m)
} else {
m := fmt.Sprintf("%d", c.m)
}
if c.h < 10 {
h := fmt.Sprintf("0%d", c.h)
} else {
h := fmt.Sprintf("%d", c.h)
}
return fmt.Sprintf("%s:%s", h, m)
}
我得到的错误是:
语法错误:意外的名称,期望分号或换行符或 }
,出现在上面的 h string
这一行。
你知道这里出了什么问题吗?我原以为我只需要使用一个临时变量来格式化整数值。
英文:
I am having a little trouble with what I though was a simple task.
I have a function that formats a struct that holds an hour and a minute value and formats it into a string.
type Clock struct {
h int
m int
}
func (c *Clock) String() string {
h string
m string
if c.m < 10 {
m := fmt.Sprintf("0%d", c.m)
} else {
m := fmt.Sprintf("%d", c.m)
}
if c.h < 10 {
h := fmt.Sprintf("0%d", c.h)
} else {
h := fmt.Sprintf("%d", c.h)
}
return fmt.Sprintf("%s:%s", h, m)
}
The error I am getting is:
syntax error: unexpected name, expecting semicolon or newline or }
for the line h string
above.
Any idea what is going on here? I figured I would simple use a temporary variable to format the int values
答案1
得分: 5
你需要声明:
var h string
var m string
在给 h
和 m
赋值时,不要使用 :=
,而是使用 =
(否则你只会在它们的内部作用域中定义变量,而不是重用之前定义的变量)
if c.m < 10 {
m = fmt.Sprintf("0%d", c.m)
} else {
m = fmt.Sprintf("%d", c.m)
}
if c.h < 10 {
h = fmt.Sprintf("0%d", c.h)
} else {
h = fmt.Sprintf("%d", c.h)
}
完整示例:play.golang.org
输出结果:Hello, playground 02:08
英文:
You need to declare:
var h string
var m string
And do not use :=
but =
when affecting values to h
and m
(or you would define those only in their inner scope, instead of reusing the variables defined before)
if c.m < 10 {
m = fmt.Sprintf("0%d", c.m)
} else {
m = fmt.Sprintf("%d", c.m)
}
if c.h < 10 {
h = fmt.Sprintf("0%d", c.h)
} else {
h = fmt.Sprintf("%d", c.h)
}
Full example: play.golang.org
Output: Hello, playground 02:08
答案2
得分: 0
声明String
方法的变量时,只需使用var
关键字进行一次声明,不要使用短变量声明(:=
)重新声明它们。例如,
package main
import "fmt"
type Clock struct {
h int
m int
}
func (c *Clock) String() string {
var (
h string
m string
)
if c.m < 10 {
m = fmt.Sprintf("0%d", c.m)
} else {
m = fmt.Sprintf("%d", c.m)
}
if c.h < 10 {
h = fmt.Sprintf("0%d", c.h)
} else {
h = fmt.Sprintf("%d", c.h)
}
return fmt.Sprintf("%s:%s", h, m)
}
func main() {}
参考资料:
英文:
Declare the String
method variables once (var
). Do not redeclare them with short variable declarations (:=
). For example,
package main
import "fmt"
type Clock struct {
h int
m int
}
func (c *Clock) String() string {
var (
h string
m string
)
if c.m < 10 {
m = fmt.Sprintf("0%d", c.m)
} else {
m = fmt.Sprintf("%d", c.m)
}
if c.h < 10 {
h = fmt.Sprintf("0%d", c.h)
} else {
h = fmt.Sprintf("%d", c.h)
}
return fmt.Sprintf("%s:%s", h, m)
}
func main() {}
References:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论