简体   繁体   中英

Golang pointer string to value

Some code I am using flags for managing the program or service. Today I got the problem, where I wanted to use this kind of declaration:

var port = flag.String("port", "", "port")

It is return back a *string type variable what I can't convert to string . How I managed the problem:

r.Run(":" + *port)

It is working but what is the best practice for that? I mean there are loads of function which is waiting string as parameter, and in this case I can't handle that.

Your port variable is of type *string (this is what flag.String() returns). To get a value of type string , there's no other way than to dereference it: *port .

You may do so at every place where you need to pass it as a string , or you may use flag.StringVar() instead:

var port string

func init() {
    flag.StringVar(&port, "port", "", "port")
}

In this case, your port variable is of type string , so no dereferencing is needed. Here you explicitly provide a *string value to the flag package to be used: the address of your variable of type string , which will be of type *string of course (so the flag package will be able to modify / set the pointed value). The flag.String() is a convenience function which allocates a string value and returns you the pointer to it.

Another option would be to dereference it once and store the string value in another variable of type string , for example:

var portp = flag.String("port", "", "port")
var port string

func main() {
    flag.Parse()
    port = *portp
    // Now you can use port which is of type string
}

But I prefer the flag.StringVar() solution.

Note that however a port is a number, you may be better off using flag.Int() or flag.IntVar() :

var port int

func init() {
    flag.IntVar(&port, "port", 0, "port")
}

You should be able to use it as is or just convert it to a string.

package main

import "fmt"
import "flag"

func main () {

    var port = flag.String("port", "", "port")
    flag.Parse()

    test(*port)

    newstring := *port

    test(newstring)
}

func test (s string) {

    fmt.Println(s)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM