Skip to content

Instantly share code, notes, and snippets.

@bentranter
Last active October 4, 2015 20:32
Show Gist options
  • Save bentranter/95d6fc63d990fb6b1092 to your computer and use it in GitHub Desktop.
Save bentranter/95d6fc63d990fb6b1092 to your computer and use it in GitHub Desktop.
Pointers in Go: Just like C 😊
#include <stdio.h>
int byVal(int i) {
i = 0;
return i;
}
int byRef(int *i) {
*i = 0;
return *i;
}
// This will print
// 0
// 0
// a: 1
// b: 0
int main() {
int a = 1;
int b = 2;
printf("%d\n", byVal(a));
printf("%d\n", byRef(&b));
printf("%d\n", a);
printf("%d\n", b);
}
// Run this code at http://play.golang.org/p/FWbp9KwBaq
package main
import "fmt"
func byVal(i int) int {
i = 0
return i
}
func byRef(i *int) int {
*i = 0
return *i
}
// This will print
// 0
// 0
// a: 1
// b: 0
func main() {
a := 1
b := 2
fmt.Println(byVal(a))
fmt.Println(byRef(&b))
fmt.Println("a: ", a)
fmt.Println("b: ", b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment