为什么我的代码直接跳转到默认情况?Go语言中的switch case语句

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

Why does my code jump straight to default? Switch case in Go

问题

我刚开始学习Go,并尝试实现switch语句。据我所知,在其他语言中,这个语句需要使用"break;",但在Go中不需要。不知何故,我的代码直接跳转到了default块。截至我写这个问题的时间,是2022年4月23日,星期六。

附言:如果有人能向我推荐一些可以免费学习Go的平台,我将不胜感激。

这是我的代码:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("星期天是哪天?")
	today := time.Now().Weekday()

	switch time.Sunday {
	case today + 0:
		fmt.Println("今天。")

	case today + 1:
		fmt.Println("明天。")

	case today + 2:
		fmt.Println("后天。")

	default:
		fmt.Println("还有很长时间。")
	}
}
英文:

I am just starting Go and tried implementing switch statement. As far as I know this statement in other languages require "break;" but not in Go. Somehow my code jumps directly into default block. By the time I am writing this question, it is 23/04/2022, Saturday.

P.S. I would be grateful if any of you could suggest me any platforms, where I can take Go courses for free.

This is my code:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("when is Sunday?")
	today := time.Now().Weekday()

	switch time.Sunday {
	case today + 0:
		fmt.Println("Today.")

	case today + 1:
		fmt.Println("Tommorow.")

	case today + 2:
		fmt.Println("In 2 days.")

	default:
		fmt.Println("Too far away.")
	}
}

答案1

得分: 2

time.Sunday 是一个值为0的常量。在你的switch语句中,你将1或2加到today上,但是当它达到6(星期六)时,值不会循环回到零。

所以你的switch语句的第二个和第三个条件永远不会成立。

下面的代码可以实现你的需求:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("星期天是哪天?")
	today := time.Now().Weekday()

	switch today {
	case time.Sunday:
		fmt.Println("今天。")

	case time.Saturday:
		fmt.Println("明天。")

	case time.Friday:
		fmt.Println("后天。")

	default:
		fmt.Println("还有很长时间。")
	}
}
英文:

time.Sunday is a const with the value 0. In your switch you add 1 or 2 to today but the value doesn't loop back around to zero after it reaches a value of 6 (Satureday).

So the second and third clause of your switch will never be true.

This does what you want:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("when is Sunday?")
	today := time.Now().Weekday()

	switch today {
	case time.Sunday:
		fmt.Println("Today.")

	case time.Saturday:
		fmt.Println("Tommorow.")

	case time.Friday:
		fmt.Println("In 2 days.")

	default:
		fmt.Println("Too far away.")
	}
}

huangapple
  • 本文由 发表于 2022年4月23日 21:21:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71980021.html
匿名

发表评论

匿名网友

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

确定