Create an instance of a struct from an imported type


(Calvin Cani) #1

I created a struct in another package in another directory. The struct name is Person. Now I want to create an instance of a person in main package and use that person like so:

func main() {
    p := Person {
		"Joe",
		"Doe",
		time.Date(1971, time.September, 1, 0, 0, 0, 0, time.UTC),
		"xxx@xxxx.com,
		"Helena",
	}
}

but it does not want to work and I cannot import the package because it just gets removed on save


(Alexander) #2

To use a type from another package, you need to prepend type with package name like this:

package main

import "yourpkg"

func main() {
	p := yourpkg.Person {
		"Joe",
		"Doe",
		time.Date(1971, time.September, 1, 0, 0, 0, 0, time.UTC),
		"xxx@xxxx.com",
		"Helena",
	}
}

(Calvin Cani) #3

I’m learning thank you very much