Golang Program to Show the Duplicate Case Error in Switch Statement


In Golang, the switch statement is used to select one of many possible code blocks to execute. The switch statement compares the expression provided in the switch statement to a list of cases, and executes the code block associated with the first case that matches the expression. In this article, we will discuss how to write a Golang program to show the duplicate case error in the switch statement.

Duplicate Case Error in Switch Statement

In Golang, a switch statement with duplicate cases will result in a compile-time error. This error occurs when two or more cases in the switch statement have the same value.

Example

For example, the following code will result in a duplicate case error −

package main

import "fmt"

func main() {
   num := 1
   switch num {
      case 1:
         fmt.Println("Case 1")
      case 2:
         fmt.Println("Case 2")
      case 1:
         fmt.Println("Case 3")
   }
}

Output

./main.go:12:12: duplicate case 1 (constant of type int) in expression switch
	./main.go:8:12: previous case

In this code, we define a variable num and use a switch statement to check its value. The switch statement has three cases, but the second and third cases have the same value, which is 1. This will result in a duplicate case error.

Golang Program to Show the Duplicate Case Error in Switch Statement

Now, let's write a Golang program to show the duplicate case error in the switch statement −

Example

package main

import "fmt"

func main() {
   num := 1
   switch num {
      case 1:
         fmt.Println("Case 1")
      case 2:
         fmt.Println("Case 2")
      case 1:
         fmt.Println("Case 3")
      default:
         fmt.Println("Default Case")
   }
}

In this program, we define a variable num and use a switch statement to check its value. The switch statement has three cases, but the second and third cases have the same value, which is 1. To show the duplicate case error, we have added a default case to the switch statement. The default case will be executed if none of the other cases match the expression in the switch statement.

Output

./main.go:12:12: duplicate case 1 (constant of type int) in expression switch
	./main.go:8:12: previous case

This error message indicates that there is a duplicate case in the switch statement. By fixing the duplicate case error, the program will work correctly and execute the correct code block based on the value of num.

Conclusion

In this article, we have discussed how to write a Golang program to show the duplicate case error in the switch statement. We have also explained what causes the error and how to fix it. By following the steps provided, you can learn how to write efficient and error-free code in Golang.

Updated on: 19-Apr-2023

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements