How to split a string and assign it to variables

前端 未结 9 1531
无人及你
无人及你 2020-12-07 10:27

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

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

but in Go it does not see

9条回答
  •  無奈伤痛
    2020-12-07 11:10

    There's are multiple ways to split a string :

    1. If you want to make it temporary then split like this:

    _

    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. Split based on struct :

      • Create a struct and split like this

    _

    type ServerDetail struct {
        Host       string
        Port       string
        err        error
    }
    
    ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port
    

    Now use in you code like ServerDetail.Host and ServerDetail.Port

    If you don't want to split specific string do it like this:

    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.

提交回复
热议问题