-2

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)
}
Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Mika
  • 1
  • 1

2 Answers2

1

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:

  1. one word is used to point to a method table for the value’s underlying type,
  2. and the other word is used to point to the actual data being held by that value.

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\n", k)
}

See this playground example

Community
  • 1
  • 1
Derlin
  • 9,572
  • 2
  • 32
  • 53
  • Almost upvoted, but mentioning the `reflect` package to someone who is obviously new to Go is... – RayfenWindspear Mar 31 '17 at 18:18
  • I don't see any other way to avoid the reflect package... And reflection is common in many languages! If you have an improvement to propose, I am happy to edit my answer (and it would be a more helpful comment). – Derlin Mar 31 '17 at 19:02
  • Type casting, Type switches, etc. Of course, this doesn't work with the struct being defined inside the function (which is certainly a mistake here). – RayfenWindspear Mar 31 '17 at 19:13
1

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

https://play.golang.org/p/cUS6ttcUy-

apxp
  • 5,240
  • 4
  • 23
  • 43