गो

2013-12-11 3 views
25

में फ़ंक्शन बॉडी के बाहर गैर-घोषणा विवरण, मैं एक एपीआई के लिए गो लाइब्रेरी का निर्माण कर रहा हूं जो JSON या XML स्वरूपित डेटा प्रदान करता है।गो

इस एपीआई के लिए मुझे हर 15 मिनट में session_id का अनुरोध करने की आवश्यकता है, और कॉल में इसका उपयोग करें। उदाहरण के लिए:

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

मेरी गो पुस्तकालय में, मैं main() समारोह के बाहर एक चर बनाने और हर API कॉल के लिए एक मूल्य के लिए यह पिंग करने का इरादा करने के लिए कोशिश कर रहा हूँ। यदि वह मान शून्य या खाली है, तो एक नई सत्र आईडी का अनुरोध करें और इसी तरह।

package apitest 

import (
    "fmt" 
) 

test := "This is a test." 

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

} 

क्या मुहावरेदार जाओ जिस तरह से एक विश्व स्तर पर सुलभ चर घोषित करने के लिए necesarilly एक निरंतर है, लेकिन नहीं?

मेरे test चर जरूरतों:

  • उसके अपने पैकेज में कहीं से भी सुलभ हो।
  • अस्थिर

उत्तर

31

बनें आप की जरूरत है

var test = "This is a test" 

:= केवल कार्यों में काम करता है और इतना है कि यह केवल पैकेज (unexported) को दिखाई देता है छोटे अक्षर 'टी' है।

एक और अधिक 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 
} 

उत्पादन

testing 
Something Else 
Type can be inferred 

वैकल्पिक रूप से, अधिक जटिल पैकेज प्रारंभिकरण के लिए या पैकेज द्वारा जो भी राज्य आवश्यक है, उसे स्थापित करने के लिए एक 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] 
} 

मुख्य चलने से पहले इनिट को बुलाया जाएगा।

+0

इस प्रकार का प्रारंभिक कार्य क्यों काम करता है? – sergserg

+0

यदि कोई प्रारंभकर्ता मौजूद है, तो प्रकार छोड़ा जा सकता है; परिवर्तक प्रारंभकर्ता के प्रकार ले जाएगा। – robbmj

7

अगर आप गलती से "समारोह" या "समारोह" या "समारोह" का उपयोग करते हैं बजाय "समारोह" आप भी प्राप्त होगा:

गैर घोषणा बयान समारोह के बाहर शरीर

इसे पोस्ट करना क्योंकि शुरुआत में मैंने यह पता लगाने के लिए अपनी खोज पर समाप्त हो गया था कि क्या गलत था।

+1

या यदि आप टाइपो func, कीवर्ड और फ़ंक्शन नाम के बीच की जगह को कम करना – JGurtz