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

How to Split Strings and Assign Variables in Go?

Susan Sarandon
Release: 2024-12-20 10:26:10
Original
767 people have browsed it

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)
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template