2013-12-11 11 views
25

Sto costruendo una libreria Go per un'API che offre dati in formato JSON o XML.Dichiarazione di non dichiarazione esterna al corpo della funzione in Go

Questa API richiede che venga richiesto un session_id ogni 15 minuti circa e che venga utilizzato nelle chiamate. Per esempio:

foo.com/api/[my-application-id]/getuserprofilejson/[username]/[session-id] 
foo.com/api/[my-application-id]/getuserprofilexml/[username]/[session-id] 

Nella mia biblioteca Go, sto cercando di creare una variabile al di fuori della main() func e l'intenzione di rumore metallico per un valore per ogni chiamata API. Se quel valore è nullo o vuoto, richiedere un nuovo ID di sessione e così via.

package apitest 

import (
    "fmt" 
) 

test := "This is a test." 

func main() { 
    fmt.Println(test) 
    test = "Another value" 
    fmt.Println(test) 

} 

Qual è il modo idiomatico Vai a dichiarare una variabile a livello globale accessibile, ma non necesarilly una costante?

miei test esigenze variabili a:

  • essere accessibili da qualsiasi punto all'interno di esso la propria confezione.
  • essere variabile

risposta

31

È necessario

var test = "This is a test" 

:= funziona solo nelle funzioni e il caso 't' è più bassa in modo che sia visibile solo per il pacchetto (quali no).

Un altro attraverso explenation

test1.go

package main 

import "fmt" 

// the variable takes the type of the initializer 
var test = "testing" 

// you could do: 
// var test string = "testing" 
// but that is not idiomatic GO 

// Both types of instantiation shown above are supported in 
// and outside of functions and function receivers 

func main() { 
    // Inside a function you can declare the type and then assign the value 
    var newVal string 
    newVal = "Something Else" 

    // just infer the type 
    str := "Type can be inferred" 

    // To change the value of package level variables 
    fmt.Println(test) 
    changeTest(newVal) 
    fmt.Println(test) 
    changeTest(str) 
    fmt.Println(test) 
} 

test2.go

package main 

func changeTest(newTest string) { 
    test = newTest 
} 

uscita

testing 
Something Else 
Type can be inferred 

In alternativa, per inizializzazioni di pacchetti più complesse o per impostare qualsiasi stato richiesto dal pacchetto GO fornisce una funzione di init.

package main 

import (
    "fmt" 
) 

var test map[string]int 

func init() { 
    test = make(map[string]int) 
    test["foo"] = 0 
    test["bar"] = 1 
} 

func main() { 
    fmt.Println(test) // prints map[foo:0 bar:1] 
} 

Init verrà chiamato prima che main venga eseguito.

+0

Perché funziona questo tipo di inizializzazione? – sergserg

+0

Se è presente un inizializzatore, il tipo può essere omesso; la variabile prenderà il tipo di inizializzatore. – robbmj

7

Se si utilizza accidentalmente "Func" o "funzione" o "Funzione" invece di "func" si riceverà anche:

dichiarazione

mancata dichiarazione al di fuori della funzione body

Pubblicare questo perché inizialmente sono finito qui sulla mia ricerca per capire cosa c'era di sbagliato.

+1

o se si utilizza typo, ommitting lo spazio tra parola chiave e nome funzione – JGurtz

Problemi correlati