Home >Backend Development >Golang >How to Split Strings and Assign Variables in Go?

How to Split Strings and Assign Variables in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 10:26:10769browse

How to Split Strings and Assign Variables in Go?

Splitting Strings and Assigning Variables in Go

Unlike Python, which allows for simultaneous string splitting and variable assignment, Go requires a slightly different approach.

Two-Step Split

One method is to split the string into a slice and then assign the values:

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := strings.Split("127.0.0.1:5432", ":")
    ip, port := s[0], s[1]
    fmt.Println(ip, port)
}

One-Step Split

Go's net package provides a convenient SplitHostPort function for splitting a host-port string directly into variables:

package main

import (
    "fmt"
    "net"
)

func main() {
    host, port, err := net.SplitHostPort("127.0.0.1:5432")
    fmt.Println(host, port, err)
}

Both approaches effectively allow you to split a string and assign the resulting values to variables in Go.

The above is the detailed content of How to Split Strings and Assign Variables in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn