I'm afk and haven't run a test yet, but it's strange.
Consulting the spec at https://go.dev/ref/spec#Package_initialization
> The entire package is initialized by assigning initial values to all its
package-level variables followed by calling all init functions in the order
they appear in the source, possibly in multiple files, as presented to the
compiler.

Unless I'm reading this wrong, this would indicate that the variable c
should have been initialized before the init function was called, and this
should have worked fine.


On Tue, Mar 10, 2026, 18:10 'andreas graeper' via golang-nuts <
[email protected]> wrote:

> hi. i see a video on youtube about cobra (cli)
> in a package c
>  c/c.go   // root-command
>  c/s.go   // sub-command
>
> --c.go-
>  var c = &cobra.Command {}
>
> --s.go--
>  var s = &cobra.Command{
>  }
>  func init(){
>   c.AddCommand( s, .. )
>  }
> go-build ok
> but if i run the program it crashes and i am told that s poinzrt is nil or
> invalid.
> so i thought that func init() is package-initialiser and maybe s is not
> initialized, so i left declaration
>  var s * command.Cobra = nil // explicit set to nil
> in package-scope and moved initialization into init function
>
> func init () {
>   s = & cobra.Command { .. }
>   if s!=nil and c!=nil {
>   c.AddCommand(s)
>   } else { panic("nilpointer") }
>  }
> but in the end, not the s was invalid but the c.
>
> if there is a package-directory c/ and a.go b.go c.go all in same 'package
> c' are they initialized in alphabetic order ? or if there is an
> init-function (i.e in b.go ) using a symbol from a.go, is then the
> init-function in a.go called before ?
>
> why initializing a pointer in package-scope is done before (success), but
> inside init-function in the order the source-files are handled (crash) ?
>
> thanks in advance, andi
>
> --
> 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 [email protected].
> To view this discussion visit
> https://groups.google.com/d/msgid/golang-nuts/95f36144-a8b7-4ad1-bf14-bcfcfacd3c23n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/95f36144-a8b7-4ad1-bf14-bcfcfacd3c23n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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 [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/CADgY6e-RfKdSoj72SyuxQhQSuf1jQ%3DMsu%2Bej7N0%3DMU2n0ANjgw%40mail.gmail.com.

Reply via email to