Perl and Go equivalents

This is a list of equivalents in Perl and Go, meant as a quick start for a Perl programmer learning Go.

Perl Go Notes
my $x
var x {}interface
In Go, {}interface can contain a general quantity.
$x = \$y
x = & y
my %x;
var x map[string]string
In Go, the type of the value of the hash needs to be explicitly specified.
my (undef, $x) = f ();
_, x := f()
An underscore is used in Go to discard return values of a function.
defined $x{key}
_, ok = x["key"]
In Go, a second argument when retrieving a hash returns a boolean which is equivalent to defined in Perl.
else if
Go does not have an elsif statement.
push @a, $b
a = append(a, b)
push @a, @b
a = append(a, b...)
In Go, it's possible to append one slice to another slice, but an ellipsis is necessary.
var x bool
Perl does not have any boolean type.
for my $y (@x)
for _, y := range x
for my $i (0..$#x) {
    my $y = $x[$i];
for i, y := range x {
use utf8;
All Go strings and identifiers are in UTF-8, so it is as if "use utf8;" in Perl was on by default. To get a non-utf-8 string in Go, one uses "bytes" rather than "string".
map { f ($_) } split //, $s
strings.Map(s, f)
scalar @x
ref $x
import "reflect"
The Go method requires the package "reflect" to be imported.
Go's cap, the capacity of an array, has no equivalent in Perl.
printf "%s", $x;
fmt.Printf("%s", x)
printf $fh "%s", $x;
fmt.Fprintf(fh, x)
substr $x, 10, 20
In Go, use slices to get substrings.
my @x = (1, 2, 3);
var x [3] int
x := (1, 2, 3)
my %x;
x := make(map[string]string)
Go has associative arrays but the type needs to be specified. A general associative array in Go has the type map[string]{}interface. For example, this is used in the Go "json" package.

Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer