I wonder how to replace *Type
by ? What address has the structure inside?
//mycode.go
package main
import "fmt"
func out(k *Type) {
fmt.Println(k)
}
func main() {
type DataIP struct{ Title, Desc string }
Data := DataIP{
"Hello!",
"Hello GO!",
}
out(&Data)
}
I am not sure to understand your question.
If you want out
to work only with structs of type DataIP
:
simply define DataIP
outside of main and use the signature func out(k *DataIP)
.
if what you want is to be able to pass any type of structure to out
:
In golang, this sort of generic methods can be implemented using the interface type. As this answer explains, an interface is a container with two words of data:
An interface can hold anything and is often used as a function parameter to be able to process many sort of inputs.
In your case, you can do:
func out(k interface{}) {
fmt.Println(k)
}
This will print &{Hello! Hello GO!}
. In case you want the &
to disappear (i.e. you always pass it pointers), you can use the reflect
package to "dereference" k
:
func out(k interface{}) {
fmt.Println(reflect.ValueOf(k).Elem())
}
which yields {Hello! Hello GO!}
Here is a playground example.
if what you want is to print the address of Data
:
you can use the %p
pattern with fmt.Printf
:
fmt.Printf("%p", &Data) // 0x1040a130
Using the out
function, you get:
func out(k interface{}) {
fmt.Printf("%p
", k)
}
See this playground example
You need to define the type DataIP outside of main()
that the type is in the scope of the package and not just inside of the main function:
package main
import "fmt"
type DataIP struct{ Title, Desc string }
func out(k *DataIP) {
fmt.Println(k)
}
func main() {
Data := DataIP{
"Hello!",
"Hello GO!",
}
out(&Data)
}