Using new and assigning variable at the same time

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

Using new and assigning variable at the same time

问题

以下是翻译好的内容:

  1. wd := new(time.Weekday)
  2. fmt.Println(wd.String())

上述两行代码返回 Sunday(星期从0开始计算)

我是否可以在 new 后面赋值?我尝试的另一种方法是:

  1. var wd time.Weekday
  2. wd = 3

这个方法返回 Wednesday(星期三)。

英文:
  1. wd := new(time.Weekday)
  2. fmt.Println(wd.String())

The above two lines return Sunday (weekdays start with a 0)

Is it possible for me to assign a value along with new ? Other method i tried is

  1. var wd time.Weekday
  2. wd = 3

this one returns Wednesday

答案1

得分: 1

你可以简单地使用time.weekday常量来实现:

wd := time.Wednesday

英文:

you can simply use the time.weekday constants for that:

wd := time.Wednesday

答案2

得分: 0

time.Weekday 是一个整数,所以你可以将其分配为整数类型(或者像Adam建议的那样使用定义的常量)。我可以问一下为什么你需要在这种情况下使用 new 吗?

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. var wd time.Weekday = 3
  8. fmt.Println(wd)
  9. }
英文:

time.Weekday is an int so you can assign it as such (or use the defined constants as Adam suggested). Can I ask why you need to use new in this situation?

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. var wd time.Weekday = 3
  8. fmt.Println(wd)
  9. }

huangapple
  • 本文由 发表于 2015年7月2日 13:00:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/31175910.html
匿名

发表评论

匿名网友

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

确定