nullpointer

67 views
Skip to first unread message

andreas graeper

unread,
Mar 10, 2026, 12:10:24 PM (2 days ago) Mar 10
to golang-nuts
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

Def Ceb

unread,
Mar 10, 2026, 12:20:38 PM (2 days ago) Mar 10
to golang-nuts
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.


--
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 visit https://groups.google.com/d/msgid/golang-nuts/95f36144-a8b7-4ad1-bf14-bcfcfacd3c23n%40googlegroups.com.

Jason E. Aten

unread,
Mar 10, 2026, 1:48:33 PM (2 days ago) Mar 10
to golang-nuts
You should post a reproducer if you want a real answer; a playground link or little repo.
Reply all
Reply to author
Forward
0 new messages