Skip to content

proposal: Go 2: spec: switch case over range #64683

Closed as not planned
Closed as not planned
@Goclipse27

Description

@Goclipse27

Go Programming Experience

Intermediate

Other Languages Experience

Java(Past), Python(Past)

Related Idea

  • Has this idea, or one like it, been proposed before?
  • Does this affect error handling?
  • Is this about generics?
  • Is this change backward compatible? Breaking the Go 1 compatibility guarantee is a large cost and requires a large benefit

Has this idea, or one like it, been proposed before?

I don't know

Does this affect error handling?

No

Is this about generics?

No , But can be handled along with generics

Proposal

When we iterate over a range and if we had to do multiple values check on switch case that looks similar to if else statement conditional check as switch statement doesn't accommodate that.

For below Example

	a := &[]struct {
		Month string
		year  int
	}{{"jan", 2000}, {"feb", 2000}, {"jan", 2023}}

	for _, cal := range *a {
		switch {
		case cal.year == 2000 && cal.Month == "jan":
			fmt.Println("1 jan 2000")
		case cal.year == 2000:
			fmt.Printf("Different Month %v 2000 \n", cal.Month)

		default:
			fmt.Println("Not on my watch")
		}
	}

I didn't write if else condition for this as we all know how to do that.

How about we have something like this in go as we iterate over all range data and a switch case for it

	switch _, cal := range *a; cal.date,cal.year,cal.Month{
           case 2000,"jan":
		fmt.Println("1 jan 200")
	   case 2000, _:
		fmt.Println("Other months in 2000")
	   default:
		fmt.Println("Not on my watch")

This can be extended to non range multiple declarations, accommodate different expressions, includes type as well and for generics.

Language Spec Changes

This changes switch statements.

Informal Change

No response

Is this change backward compatible?

Yes

Orthogonality: How does this change interact or overlap with existing features?

This brings in multiple values check against case statement

Would this change make Go easier or harder to learn, and why?

Easy

Cost Description

No Cost

Changes to Go ToolChain

golang language error check static and other.

Performance Costs

Don't know

Prototype

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions