简体   繁体   English

Go中同一包中的多个文件

[英]Multiple files in same package in Go

I'm writing my first Go code which among other things, sends an email. 我正在编写我的第一个Go代码,该代码除其他外将发送电子邮件。 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 . 在发现net/smtp软件包仅支持Plain Auth (但是某些供应商(如Outlook)不支持它)之后,我要求一种解决方案,并指出了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 . 该代码的工作原理很吸引人,但是由于它不是我自己编写的,因此我想将其添加到一个单独的文件中,然后在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. 我以为只要这些文件位于同一目录中,我就可以有许多*.go文件,但似乎*.go If I just create a file with the content of that gist, the compiler fails because expected package, found import . 如果我仅创建具有该要点内容的文件,则编译器将失败,因为expected package, found import If I add something like package auth , then it fails because found packages auth (auth.go) and main (main.go) 如果我添加类似package auth ,则它将失败,因为found packages auth (auth.go) and main (main.go)

So, what's the general practice in this situations? 那么,这种情况下的一般做法是什么? Just create packages for everything? 只是为所有内容创建软件包?

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. 目录中只能有一个软件包,并且看起来不需要软件包,因此您可以将其放在单独的文件中,然后在package main目录中添加package main Having a main package and putting everything under it works up to a point. 拥有一个main包,并将所有内容放置在一定程度上。 As things get larger, you have to break it up into self-contained packages. 随着事情变大,您必须将其分解成独立的程序包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM