Split a string only by the first element in golang

Issue

I’m trying to parse git branch names and split them so I can seperate the remote and the branch name

Previously I just split on the first slash:

func ParseBranchname(branchString string) (remote, branchname string) {
    branchArray := strings.Split(branchString, "/")
    remote = branchArray[0]
    branchname = branchArray[1]
    return
}

But I forgot that some folks use slashes in git branch names as well, multiple even!

Right now I’m taking the first element in the slice from the split, then moving every element one done and merging back on the slash:

func ParseBranchname(branchString string) (remote, branchname string) {
    branchArray := strings.Split(branchString, "/")
    remote = branchArray[0]

    copy(branchArray[0:], branchArray[0+1:])
    branchArray[len(branchArray)-1] = ""
    branchArray = branchArray[:len(branchArray)-1]

    branchname = strings.Join(branchArray, "/")
    return
}

Is there a cleaner way to do this?

Solution

Use strings.SplitN with n=2 to limit the result to two substrings.

func ParseBranchname(branchString string) (remote, branchname string) {
    branchArray := strings.SplitN(branchString, "/", 2)
    remote = branchArray[0]
    branchname = branchArray[1]
    return
}

Answered By – Jonathon Reinhart

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.