Programming

Golang에서 문자열을 분할하여 변수에 할당하는 방법은 무엇입니까?

procodes 2020. 6. 20. 12:45
반응형

Golang에서 문자열을 분할하여 변수에 할당하는 방법은 무엇입니까?


파이썬에서는 문자열을 분할하여 변수에 할당 할 수 있습니다.

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

그러나 Golang에서는 작동하지 않는 것 같습니다.

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

질문 : 문자열을 분할하고 한 번에 값을 할당하는 방법은 무엇입니까?


예를 들어 두 단계

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>

go융통성이 있기 때문에 자신만의 python스타일 분할을 만들 수 있습니다 ...

package main

import (
    "fmt"
    "strings"
    "errors"
)

type PyString string

func main() {
    var py PyString
    py = "127.0.0.1:5432"
    ip, port , err := py.Split(":")       // Python Style
    fmt.Println(ip, port, err)
}

func (py PyString) Split(str string) ( string, string , error ) {
    s := strings.Split(string(py), str)
    if len(s) < 2 {
        return "" , "", errors.New("Minimum match not found")
    }
    return s[0] , s[1] , nil
}

RemoteAddrfrom 와 같은 필드의 IPv6 주소는 http.Request"[:: 1] : 53343"으로 형식이 지정됩니다.

그래서 잘 net.SplitHostPort작동합니다 :

package main

    import (
        "fmt"
        "net"
    )

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

        host2, port, err := net.SplitHostPort("[::1]:2345")
        fmt.Println(host2, port, err)

        host3, port, err := net.SplitHostPort("localhost:1234")
        fmt.Println(host3, port, err)
    }

출력은 다음과 같습니다

127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>

문자열을 분할하는 방법에는 여러 가지가 있습니다.

  1. 임시로 만들고 싶다면 다음과 같이 나누십시오.

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. 구조체를 기준으로 분할 :

    • 구조체를 만들고 이렇게 나눕니다

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

지금과 같은 당신의 코드에서 사용 ServerDetail.Host하고ServerDetail.Port

특정 문자열을 나누지 않으려면 다음과 같이하십시오.

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.


package main

import (
    "fmt"
    "strings"
)

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

Here is the definition for strings.Split

// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
//
// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.
//
// If sep is empty, Split splits after each UTF-8 sequence. If both s
// and sep are empty, Split returns an empty slice.
//
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }

What you are doing is, you are accepting split response in two different variables, and strings.Split() is returning only one response and that is an array of string. you need to store it to single variable and then you can extract the part of string by fetching the index value of an array.

example :

 var hostAndPort string
    hostAndPort = "127.0.0.1:8080"
    sArray := strings.Split(hostAndPort, ":")
    fmt.Println("host : " + sArray[0])
    fmt.Println("port : " + sArray[1])

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

참고URL : https://stackoverflow.com/questions/16551354/how-to-split-a-string-and-assign-it-to-variables-in-golang

반응형