Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Uday Yadav
Uday Yadav

Posted on

     

Things Golang do differently

weird at first but makes sense

Formatting

  • usegofmt to format packages

Commentary

  • Go uses c like comments// or/* */
  • Every Function/Struct/Variable that you have to export, name it so that first letter is capital
  • Package name
    • short, concise, evocative
    • the package in src/encoding/base64 is imported as "encoding/base64" but has name base64, not encoding_base64 and not encodingBase64.

Getters & Setters

  • Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so.
owner:=obj.Owner()ifowner!=user{obj.SetOwner(user)}
Enter fullscreen modeExit fullscreen mode

Naming

Interface Naming
By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.

Variable Naming

  • Finally, the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multi word names
  • Ina := declaration a variable v may appear even if it has already been declared, provided:this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
  • The corresponding value in the initialisation is assignable to v, and there is at least one other variable that is created by the declaration

Indentation

ifi<f(){g()}ifi<f()// wrong!{// wrong!g()}
Enter fullscreen modeExit fullscreen mode

Control Structure

  • There is no do or while loop, only a slightly generalised for; switch is much better If. In Go a simple if looks like this:
ifx>0{returny}
Enter fullscreen modeExit fullscreen mode
  • Mandatory braces encourage writing simple if statements on multiple lines. It's good style to do so anyway, especially when the body contains a control statement such as a return or break. Since if and switch accept an initialisation statement, it's common to see one used to set up a local variable.
iferr:=file.Chmod(0664);err!=nil{log.Print(err)returnerr}
Enter fullscreen modeExit fullscreen mode

Re-declaration and Re-assignment

The last example in the previous section demonstrates a detail of how the := short declaration form works. The declaration that calls os.Open reads,

f,err:=os.Open(name)
Enter fullscreen modeExit fullscreen mode
  • This statement declares two variables, f and err. A few lines later, the call to f.Stat reads,
d,err:=f.Stat()
Enter fullscreen modeExit fullscreen mode

-​ which looks as if it declares d and err. Notice, though, that err appears in both statements. This duplication is legal: err is declared by the first statement, but only re-assigned in the second. This means that the call to f.Stat uses the existing err variable declared above, and just gives it a new value.

Range

  • If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop.
forkey,value:=rangeoldMap{newMap[key]=value}
Enter fullscreen modeExit fullscreen mode
  • If you only need the first item in the range (the key or index), drop the second:
forkey:=rangem{ifkey.expired(){delete(m,key)}}
Enter fullscreen modeExit fullscreen mode
  • If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first:
sum:=0for_,value:=rangearray{sum+=value}
Enter fullscreen modeExit fullscreen mode

Switch in Golang

  • Go's switch is more general than C's.
  • It's therefore possible—and idiomatic—to write an if-else-if-else chain as a switch.
funcunhex(cbyte)byte{switch{case'0'<=c&&c<='9':returnc-'0'case'a'<=c&&c<='f':returnc-'a'+10case'A'<=c&&c<='F':returnc-'A'+10}return0}
Enter fullscreen modeExit fullscreen mode
  • There is no automatic fall through, but cases can be presented in comma-separated lists.
funcshouldEscape(cbyte)bool{switchc{case' ','?','&','=','#','+','%':returntrue}returnfalse}
Enter fullscreen modeExit fullscreen mode

Type Switch

  • A switch can also be used to discover the dynamic type of an interface variable
vartinterface{}t=functionOfSomeType()switcht:=t.(type){default:fmt.Printf("unexpected type %T\n",t)// %T prints whatever type t hascasebool:fmt.Printf("boolean %t\n",t)// t has type boolcaseint:fmt.Printf("integer %d\n",t)// t has type intcase*bool:fmt.Printf("pointer to boolean %t\n",*t)// t has type *boolcase*int:fmt.Printf("pointer to integer %d\n",*t)// t has type *int}
Enter fullscreen modeExit fullscreen mode

Functions

  • Multiple return values
funcsquareRoot(numint)(nfloat,errerror)// orfuncsquareRoot(numint)(float,error)// to return error if num < 0// named return
Enter fullscreen modeExit fullscreen mode

Defer

  • Go's defer statement schedules a function call (the deferred function) to be run immediately before the function exits.
funcfileContent(filenamestring)(string,error){f,err:=os.Open(filename)iferr!=nil{return"",err}// defer will run the function just before exiting the function fileContentsdeferf.Close()// something with return}
Enter fullscreen modeExit fullscreen mode
  • Deferring a call to a function such as Close has two advantages.
    • First, it guarantees that you will never forget to close the file, a mistake that's easy to make if you later edit the function to add a new return path.
    • Second, it means that the close sits near the open, which is much clearer than placing it at the end of the function.

For Example :

fori:=0;i<5;i++{deferfmt.Printf("%d ",i)}
Enter fullscreen modeExit fullscreen mode

Deferred functions are executed in LIFO order, so this code will cause4 3 2 1 0 to be printed when the function returns
A more plausible example is a simple way to trace function execution through the program. We could write a couple of simple tracing routines like this:

functrace(sstring){fmt.Println("entering:",s)}funcuntrace(sstring){fmt.Println("leaving:",s)}// Use them like this:funca(){trace("a")deferuntrace("a")// do something....}
Enter fullscreen modeExit fullscreen mode

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ndiecodes profile image
Ndifreke Friday
A Javascript Lover || Laravel Advocate || Continuous Learner || Software Developer
  • Joined

I love this!

CollapseExpand
 
aalphaindia profile image
Pawan Pawar
I am founder of Aalpha Systems, 16 years of tech experience, I love writing on latest tech trends AI, ML, Blockchain etc
  • Location
    Bangalore, India
  • Work
    Entrepreneur at Aalpha
  • Joined

Keep sharing!

CollapseExpand
 
cmelgarejo profile image
Christian Melgarejo
Dev guy, breaks things, fixes them afterwards, usually working as intended or having side effects... I call those: features!
  • Joined

NIce notes!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Engineer
  • Location
    New Delhi
  • Work
    Student at GGSIPU
  • Joined

More fromUday Yadav

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp