user4093955
user4093955

Reputation:

Multiple files in same package in Go

I'm writing my first Go code which among other things, sends an email. After finding out that the package net/smtp only supports Plain Auth (but some providers like outlook doesn't support it), I asked for a solution and got pointed out to https://gist.github.com/andelf/5118732.

That code works like a charm, but as it's not something written by myself, I would like to add it in a separate file and just reference it in my main.go.

What's the right approach to have multiple files in the same package? I don't want to create a different package just for that code, first because it's not mine, and secondly, because I think it's an "overkill" approach, isn't it?

I thought that as long as the files are in the same directory, I could have many *.go files, but it seems it's not working out. If I just create a file with the content of that gist, the compiler fails because expected package, found import. If I add something like package auth, then it fails because found packages auth (auth.go) and main (main.go)

So, what's the general practice in this situations? Just create packages for everything?

Upvotes: 7

Views: 12928

Answers (2)

PixelsTech
PixelsTech

Reputation: 3347

If your current working directory is in GOPATH, then you can just add new go file with same package name main.

If your current working directory is not in GOPATH, you can still put them in multiple go files and when you run the program, you should use go run *.go instead of just go run main.go.

There are also other options which you can refer Run code with multiple files in the same main package in GoLang for detail.

Upvotes: 5

Burak Serdar
Burak Serdar

Reputation: 51622

You can have only one package in a directory, and it looks like you don't need a package for this addition, so you can simply put that in a separate file, and add package main at the top. Having a main package and putting everything under it works up to a point. As things get larger, you have to break it up into self-contained packages.

Upvotes: 9

Related Questions