如何拆分字符串并将其分配给变量 [英] How to split a string and assign it to variables

查看:26
本文介绍了如何拆分字符串并将其分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,可以拆分字符串并将其分配给变量:

In Python it is possible to split a string and assign it to variables:

ip, port = '127.0.0.1:5432'.split(':')

但在 Go 中它似乎不起作用:

but in Go it does not seem to work:

ip, port := strings.Split("127.0.0.1:5432", ":")
// assignment count mismatch: 2 = 1

问题:如何一步拆分字符串并赋值?

Question: How to split a string and assign values in one step?

推荐答案

两个步骤,例如

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)
}

输出:

127.0.0.1 5432

一步,例如

package main

import (
    "fmt"
    "net"
)

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

输出:

127.0.0.1 5432 <nil>

这篇关于如何拆分字符串并将其分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆