How to import one field from package, etc

136 views
Skip to first unread message

Alex Mills

unread,
Sep 23, 2020, 1:46:05 PM9/23/20
to golang-nuts
Using node.js, we might have this:

const z = new Z();
exports.z = z

and then in another file we can import

import {z} from '../z'

with Golang, I am trying to do something similar:

package log


// create an instance
var log = Logger.create()

// export the methods
var Info = log.Info
var Warn = log.Warn
var Error = log.Error

and then we import it like 


func init(){
   log.Info("something")
   log.Warn("something")
}

/// ===========

basically what I am asking is if there is a way to create an instance and access it's methods - so that in my code I don't have to do:


but instead I can do:

log.Info()

hope the question makes sense.






Jason Phillips

unread,
Sep 23, 2020, 2:58:46 PM9/23/20
to golang-nuts
Did you try your own suggestion? It seems to work fine: https://play.golang.org/p/KVo5COKj2ii

Alex Mills

unread,
Sep 23, 2020, 4:33:39 PM9/23/20
to Jason Phillips, golang-nuts
It works temporarily, but then I have to manually update each file that imports + exports the methods, it won't "just work" with new versions of the library that gets imported, right?


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/d2f2125f-9260-4268-ac31-cfe738dc3f5en%40googlegroups.com.

Jason Phillips

unread,
Sep 24, 2020, 2:11:13 AM9/24/20
to golang-nuts
To answer the title question: no, there's no way to limit an imported package to a subset of its exported identifiers. But, given the example provided, it seems the suggested solution works exactly as you desire.

You can give a local identifier to an imported package (e.g. https://play.golang.org/p/WJChIJoMMys ) or you can bring another package's exported identifiers into the current package's scope with "." as a package name (e.g. https://play.golang.org/p/3IyGkPNJZMx ) but I don't think either is what you're asking for.

Can you provide any more context as to what your end goal is and why the using the package name to access your identifiers is a problem?

Reply all
Reply to author
Forward
0 new messages