Introduction
An article with zero words and an article whose word count we haven't calculated are two
different things. If we store both as 0, our publishing application loses that difference
before it decides what message to show.
PHP gives us familiar ways to express this distinction, including a nullable ?int parameter.
Go asks us to think about the type of each variable and the value it has before we assign
anything ourselves.
This is the second article in Go for PHP Developers. In the
first article,
we built a command that prints a publication message. Let's extend that example while
working through type inference, conversions, zero values, and our first use of nil.
We only need enough pointer syntax to represent an optional word count. Collections get their own article next, and copying values and changing data through pointers come later.
Set Up the Example
The examples use Go 1.27.4, the latest stable release listed in the
official downloads feed when checked on November 26, 2026.
They use only the standard library. Check your installation with go version, or follow
the Go installation instructions first.
Start in a fresh directory so these experiments don't change the program from Part 1:
mkdir publishing-types
cd publishing-types
go mod init example.com/publishing
Create main.go:
package main
import "fmt"
func main() {
title := "Learning Go"
fmt.Println(title)
}
Run it with go run .. It prints Learning Go.
Until we assemble the final program, each short example below replaces the body of
main. Keep the package declaration and the fmt import. Blocks labelled as invalid
are deliberate compiler experiments and should be restored before continuing.
A Variable Keeps Its Type
PHP type declarations let us constrain parameters, return values, and properties. An ordinary local PHP variable can still hold an integer after previously holding a string. Go gives that local variable a fixed type too.
These declarations all create a string variable:
var title string = "Learning Go"
var subtitle = "Types and Values"
author := "Wendell"
fmt.Printf("%T %T %T\n", title, subtitle, author)
The output is:
string string string
var title string names the type explicitly. In the other two declarations, the compiler
infers string from the initial value. Type inference saves us from writing the type
name, while the compiler still checks later assignments.
For a new local variable with an initial value, I would usually use :=. Use = when
assigning another value to an existing variable:
title := "Learning Go"
title = "Learning Go Types"
fmt.Println(title)
Try replacing the second line with title = 42. That version fails to compile because
an integer cannot be assigned to this string variable. Writing title := 42 in the
same block also fails, because this short declaration introduces no new variable.
The distinction becomes useful when reading code. := declares at least one new variable
in its block. = assigns to variables that already exist. Short declarations are only
allowed inside functions, while var also works at package level. The
variable declaration rules describe how
the compiler selects the type.
Choose Types for the Values You Have
Our publication message needs text, a word count, and eventually a publication flag. For now, these types cover those needs:
stringholds text, such as the title"Learning Go".intholds whole numbers, such as a word count of1200.boolholdstrueorfalse, such as whether an article is published.float64holds floating-point numbers, such as an estimated reading time of4.8minutes.
Go also has integers with explicit widths, such as int32 and int64. int has either
32 or 64 bits, depending on the target. For this small in-memory word count, int is
enough. If we later read a database value or call an API, its declared types become part
of that decision. See the numeric type definitions
for the complete set and their ranges.
An integer literal used with := gives us an int. A floating-point literal such as
4.8 gives us a float64. We can inspect both with %T:
wordCount := 1200
readingMinutes := 4.8
published := false
fmt.Printf("%T %T %T\n", wordCount, readingMinutes, published)
The output is int float64 bool.
A condition must be a boolean expression. PHP lets us use a string or integer as a condition according to its boolean conversion rules. Go requires us to say what we mean:
title := "Learning Go"
wordCount := 0
if title != "" && wordCount == 0 {
fmt.Println("The article has a title but no words")
}
There are no parentheses around the condition, and the braces are required. && means
both comparisons must be true. Replacing the condition with if wordCount is deliberately
invalid Go. Use wordCount > 0, wordCount == 0, or whichever comparison matches the rule.
Convert Values Explicitly
Suppose we estimate reading time at 250 words per minute. Both operands below are integers, so division produces an integer result:
wordCount := 1200
wordsPerMinute := 250
wholeMinutes := wordCount / wordsPerMinute
readingMinutes := float64(wordCount) / float64(wordsPerMinute)
fmt.Printf("whole=%d estimate=%.1f\n", wholeMinutes, readingMinutes)
The output is:
whole=4 estimate=4.8
float64(wordCount) converts the value to float64. It leaves wordCount itself as
an int. We convert before dividing so the calculation uses floating-point operands.
Converting the result of the integer division would only turn 4 into 4.0.
The same explicitness applies between integer types. This replacement body is deliberately invalid:
wordCount := 1200
var storedCount int64 = wordCount
fmt.Println(storedCount)
Restore the example by changing the assignment to var storedCount int64 = int64(wordCount).
An int variable isn't automatically assignable to an int64 variable, even on a target
where both have the same width. An untyped constant is different. var storedCount int64 = 1200
works because that constant is representable by int64.
An explicit conversion doesn't promise that information is preserved:
readingMinutes := 4.8
wholeMinutes := int(readingMinutes)
fmt.Println(wholeMinutes)
It prints 4. For a floating-point value within the destination integer's range, the
conversion discards the fraction towards zero. Narrowing an integer can also discard
bits. Choose a conversion because it expresses the intended calculation, and validate
external values before relying on their range. The
conversion rules define these behaviours.
Text needs a separate decision. string(65) produces "A", the string for that Unicode
code point. It doesn't format the decimal number. Use
strconv.Itoa for integer-to-decimal text and
strconv.Atoi to parse decimal text into an int.
Parsing can fail, which is a reason to handle its returned error rather than treating
all input as a cast. We'll work through error handling in Part 7.
Every Declared Variable Starts With a Value
We don't have to provide an initial value in a var declaration:
var title string
var wordCount int
var published bool
var readingMinutes float64
fmt.Printf("title=%q words=%d published=%t minutes=%.1f\n",
title, wordCount, published, readingMinutes)
The output is:
title="" words=0 published=false minutes=0.0
Each variable has its type's zero value. Strings start as "", numeric types as
zero, and booleans as false. %q prints the title as a quoted string, making the empty
value visible. The zero-value specification
also explains how this initialisation applies to the elements and fields of composite values.
If you know PHP typed properties, this difference matters. A PHP typed property declared
without a default can remain uninitialised, and reading it in that state throws an Error.
Even a nullable typed property needs initialisation before a read. The
PHP property documentation
shows that behaviour. Our Go variables above are already initialised and safe to read.
That says nothing about whether the values satisfy our publishing rules. An empty title
is a valid string, but we still need to reject it when preparing an article. Likewise,
wordCount == 0 cannot tell us whether somebody counted the words. The variable contains
the same integer either way.
I would avoid assigning a special value such as -1 to mean "not counted" here. We'd
have to carry that convention into every function that reads the count. Let's represent
absence in the type instead.
Nil Depends on the Type
nil is the zero value for pointers, slices, maps, functions, channels, and interfaces.
We haven't covered most of those yet. For now, the important restriction is that nil
isn't a value we can assign to every type.
An int cannot be nil. Neither can a string or a bool. For these types, absence
needs a separate representation from zero, "", or false.
For our optional count, declare a pointer to an integer:
var wordCount *int
fmt.Println(wordCount == nil)
It prints true. *int is the type "pointer to an int". The pointer can refer to an
integer variable, or it can be nil, meaning it refers to no integer variable.
We need two more pieces of syntax to use it:
count := 0
var wordCount *int = &count
fmt.Println(wordCount == nil)
fmt.Println(*wordCount)
The output is false, then 0. &count obtains a pointer to count. In the expression
*wordCount, the * reads the integer through that pointer, which is called
dereferencing. Here we know the pointer is non-nil because we just assigned &count.
The type annotation and the expression use the same symbol in different roles. *int
names a pointer type. *wordCount accesses the pointed-to value. We'll revisit pointers
and mutation in Part 4.
For our example, the states now look like this:
wordCount *int
|
+-- nil -------------- no count supplied
|
+-- points to 0 ------ counted, article is empty
|
+-- points to 1200 --- counted, article has 1200 words
The second state has a value, even though that value is zero. That is the distinction
we couldn't recover from a plain int.
Dereferencing a nil pointer causes a runtime panic. Check for nil before reading a
pointer that may be absent. Also, wordCount := nil fails to compile because nil
alone doesn't give the compiler a type to infer. var wordCount *int provides the type.
Put the Distinction Into Our Publication Message
Let's use those states to decide what message our command prints. We still aren't publishing or saving anything. The function reports whether a title and supplied count meet our example's rules.
Create message.go:
package main
import "fmt"
func publicationMessage(title string, wordCount *int) string {
if title == "" {
return "Draft needs a title"
}
if wordCount == nil {
return "Word count unknown: " + title
}
if *wordCount <= 0 {
return "Draft needs content: " + title
}
return fmt.Sprintf("Ready to publish: %s (%d words)", title, *wordCount)
}
The nil check returns before the function reaches either dereference. The next condition
rejects zero and negative counts. We don't need an else after a branch that returns.
These rules are deliberately small. An empty string fails the title check, but a title containing only spaces passes it. The function also trusts a positive count supplied by its caller. Calculating words and validating a complete article are separate work.
Replace the complete main.go with:
package main
import "fmt"
func main() {
title := "Learning Go"
var unknownCount *int
emptyCount := 0
wordCount := 1200
fmt.Println(publicationMessage(title, unknownCount))
fmt.Println(publicationMessage(title, &emptyCount))
fmt.Println(publicationMessage(title, &wordCount))
}
Run go run .. The output is:
Word count unknown: Learning Go
Draft needs content: Learning Go
Ready to publish: Learning Go (1200 words)
If you're continuing the original project instead of using the fresh directory, replace
its old message.go, main.go, and message_test.go with the versions in this article.
The function now takes a second argument, so the original test needs updating too.
Test Absence Separately From Zero
Create message_test.go:
package main
import "testing"
func TestPublicationMessageWithoutCount(t *testing.T) {
got := publicationMessage("Learning Go", nil)
want := "Word count unknown: Learning Go"
if got != want {
t.Fatalf("publicationMessage() = %q, want %q", got, want)
}
}
func TestPublicationMessageWithEmptyArticle(t *testing.T) {
count := 0
got := publicationMessage("Learning Go", &count)
want := "Draft needs content: Learning Go"
if got != want {
t.Fatalf("publicationMessage() = %q, want %q", got, want)
}
}
func TestPublicationMessageWithContent(t *testing.T) {
count := 1200
got := publicationMessage("Learning Go", &count)
want := "Ready to publish: Learning Go (1200 words)"
if got != want {
t.Fatalf("publicationMessage() = %q, want %q", got, want)
}
}
func TestPublicationMessageWithoutTitle(t *testing.T) {
got := publicationMessage("", nil)
want := "Draft needs a title"
if got != want {
t.Fatalf("publicationMessage() = %q, want %q", got, want)
}
}
func TestPublicationMessageWithNegativeCount(t *testing.T) {
count := -1
got := publicationMessage("Learning Go", &count)
want := "Draft needs content: Learning Go"
if got != want {
t.Fatalf("publicationMessage() = %q, want %q", got, want)
}
}
The tests give absence and zero different expectations. They also check that an empty
title takes priority, and that a negative count doesn't produce a ready message.
Using nil directly as an argument works because the parameter supplies the *int type.
Format, test, and build the package:
go fmt ./...
go test ./...
go vet ./...
go build -o publisher .
./publisher
The tests report ok for example.com/publishing, and the executable prints the same
three lines as go run .. These tests check message selection. They don't check whether
an article's reported word count is accurate.
Where the PHP Comparison Stops
A PHP ?int parameter and our Go *int parameter both let us accept absence alongside
an integer. Their mechanics differ. The Go value is a pointer, and another function
could use it to change the integer it points to. We only read it in this example.
There are other ways to represent optional data in Go, including a value paired with
a presence flag. We'll encounter that approach with map lookups next time.
Slices, maps, and interfaces can also be nil, but the operations available on each type
differ. We'll explain those rules in the articles that introduce them. The pointer check
in our function is specific to the *int parameter we're reading.
For now, ask what type a variable has, what its zero value is, and which operations that value allows. A comparison with PHP is useful only while it preserves those details.
Conclusion
Try removing the nil guard in publicationMessage, then run the tests. The missing-count
test reaches a nil dereference and panics. Restore the guard and change the empty count
to a positive number to see why those inputs need separate tests.
I would keep this example in one package and let the tests describe the rules we have so far. We can introduce a richer article model when we need to keep its data together.
Next in Go for PHP Developers: Beyond the PHP Array. We'll compare arrays, slices, and maps, including how a map lookup distinguishes a missing entry from a zero value.
I hope that you liked this article and if you do, don't forget to share this article with your friends!!! See ya!