How golang from the end of the for loop for loop inside the switch

Today go when it came to writing a magic question, go inside because the default switch with break, so I assume that when the switch after a certain condition is reached, will be able to use break out of the current cycle. code show as below:

for {
		switch{
		case i>j:
			break
		case i <= r && nums[i] < v:
			i++
		case j >= l+1 && nums[j] > v:
			j--
		default:
			swap(nums,i,j)
			i++
			j--
		}
	}
	swap(nums,l,j)
	return j

I want i>jthe time out of the loop, execute the following swap the code, the test results have not work, go remembered the switch default break comes, I manually write the break is equivalent to the end of the second switch, but for the outer loop or It continues to run, not achieve the desired effect, a hidden trap.

Internet search a bit, go there are several solutions. The first is to set the loop condition flag when conditions agreed to modify the value of the flag, which is relatively simple, but it seems not enough advanced.

The second is to use tag plus break, give a name for the cycle as a tag, set here Loop, when out of the loop when required, with the break Loopcan out of the loop.

Loop:
	for {
		switch{
		case i>j:
			break Loop
		case i <= r && nums[i] < v:
			i++
		case j >= l+1 && nums[j] > v:
			j--
		default:
			swap(nums,i,j)
			i++
			j--
		}
	}
	swap(nums,l,j)
	return j

The third is goto, with the second principle is similar to the code execution to jump out of the need to add a tag, here set End, when out of use goto Endyou can jump to the appropriate code.

for {
		switch{
		case i>j:
			goto End
		case i <= r && nums[i] < v:
			i++
		case j >= l+1 && nums[j] > v:
			j--
		default:
			swap(nums,i,j)
			i++
			j--
		}
	}

	End:
	swap(nums,l,j)
	return j

Do not know java and c ++ has no similar wording, when the previous study were used first, if there are good suggestions, comments can tell me ~

Released three original articles · won praise 0 · Views 28

Guess you like

Origin blog.csdn.net/sinat_34896047/article/details/104007878