Export imports with Golang

Viewed 7733

Not sure if this is impossible with Golang. With Node.js, I would do it like so:

import * as person from './person';
export {person};

with Golang I have models.go:

package models

import (
    "huru/models/person"
)

is it possible to export person from this models.go file, in a person namespace like with TypeScript/node.js?

4 Answers

[I]s it possible to export person from this models.go file, in a person namespace like with TypeScript/node.js?

No.

@MrCholo there is a little difference in golang concept here. The golang structs available under namespace scoped.

Like as per example

package models

// struct name should starts with Capital letter to export
type Person struct {
    Name string
    age int
}

The Person struct will be available in all files scoped under same namespace(ex. models). You don't need to import that.

But if you would like to access outside the models namespace you'll have to import the package models and access the Person object using that.

ex.

package anotherpackage

import (
    "<path to models>/models"
)

var perObj models.Person  // here is how you can access the Person struct

Let me know if it's still not clear to you.

You cannot just pass through a complete package. You can pass through different types by making your own types based on them. If there was a person.Person:

package models

import (
    "huru/models/person"
)

type Person person.Person

//or

type EmbeddedPerson struct{
    person.Person
    additional string
}

This has the advantage of allowing you to add your own functions

func (p Person) CustomFunc() {}

Here is a playground link that shows some of the nuances of this: https://play.golang.org/p/1aLOcmsXHV2

Yes, We can export struct from file to another file(or package) like other languages.

person.go

package models

// struct name should starts with Capital letter to export
type Person struct {
    Name string
    age int
}

If the importing file is in the same package(models), then no need to import. Straight away you can use like this:

details.go

package models

var perObj Person

func abc() {
    perObj.Name = "xyz"
}

If the importing file is in some other package, then import models package.

businesslogic.go

package logic

import (
    "../../models"
)

var perObj Person

func abc() {
    perObj.Name = "xyz"
}
Related