Created
January 17, 2021 12:32
-
-
Save pszalawinski/621df9f7509ead33fe3f49d320499752 to your computer and use it in GitHub Desktop.
Go functions #go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BASIC VIEW: | |
func name(paramerters) whatToReturn { | |
//body | |
return whatToReturn | |
} | |
----------------------- | |
PASSING PARAMETERS | |
we can pass more than one argument and Go code will create slice from this arguments: | |
func main() { | |
sum(1, 2, 3, 4) | |
} | |
func sum(values ...int) { | |
result := 0 | |
for _, v := range values { | |
result += v | |
} | |
fmt.Println(result) | |
} | |
but it can only be one of this and need to be passed as last argument for ex. | |
func sum(msg string, values ...int) {} | |
if we are passing more than one parameter but they are the same typy we can split it by comma | |
func passing(foo, bar, baz, yzy int) //we are passing 4 parameters all are integers | |
----------------- | |
RETURNIG VALUES | |
func divide(a, b float64) (float64, error) //returnig 2 values { | |
if b == 0.0 { | |
return 0.0 , fmt.Errorf("cannot divide by zero") | |
} | |
reuturn a/b, nil | |
} | |
and then we need to also "take" 2 calues as return in our main function: | |
func main(){ | |
d , err := divide (5.0, 0.0) | |
if err != nil{ | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(d) | |
} | |
----------- | |
ANONYMOUS FUNTION | |
we can invoke functions inside objects | |
func(t){ | |
body | |
}() | |
----- | |
when th epointer are passsed int, the function can change the value in the cellar | |
funct foo() (int, error) | |
the (result type, error) paradigm is a verry common idiom | |
METHODS | |
methods are special functions which return functions | |
func (s struct) someFunction(){} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment