Expected declaration, found 'package'

2,510 views
Skip to first unread message

Tong Sun

unread,
Apr 26, 2017, 11:51:50 AM4/26/17
to golang-nuts
Hi, 

I'm trying to put different code collection into the same Go source file, (from here, if you want to know), because the knowledge is related thus better keep in one demo file instead of several. However, the challenge to me is that, it keeps reusing the same variable name for different purposes (which I think IS good practice). E.g., 

In one section the type A is defined as 

type A struct {
}

In another section the type A is defined as 

type A struct {
    name string
}


In C#, this is not a problem at all, as I can just put different cases into different namespaces. 

How to do it (putting different code collection into the same Go source file) in Go? 

I tried to separate different sections with 

package next_section

but got the error 

expected declaration, found 'package'

What's the easiest way to do it? please help. 

Thanks




Thomas Bushnell, BSG

unread,
Apr 26, 2017, 11:52:56 AM4/26/17
to Tong Sun, golang-nuts
A single Go source file is not allowed to be in more than one package.

--
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.
For more options, visit https://groups.google.com/d/optout.

Lutz Horn

unread,
Apr 26, 2017, 3:28:24 PM4/26/17
to golan...@googlegroups.com
> However, the challenge to me is that, it keeps reusing the same
> variable name for different purposes (which I think IS good
> practice). E.g.,

For a blog or a tutorial that expands an example, this is fine. But it
is bad practice when designing a library.

> In one section the type A is defined as
>
> type A struct { }
>
> In another section the type A is defined as
>
> type A struct { name string }

Why? If A has a name, why define A without it?

> How to do it (putting different code collection into the same Go
> source file) in Go?

You can't do that. An exported name A must be unique in a package.

Regards

Lutz

Reply all
Reply to author
Forward
0 new messages