Recently I came across something interesting in Go. I wrote the following code to read logs from a log file in the server.

func readLogsFromPartition(partition int) []LogEntry {
var logs []LogEntry // Creating an innocent slice
logs = ReadFromFile()

return logs // Returning the slice
}

func main() {
logs := readLogsFromPartition(1) // Using the slice in the main func
}

I compiled the program and ran it, and it worked. But after I took a step back and looked at it, I couldn’t make sense of why it worked. Why am I able to return a value that was created on the local function back to the main function?

If you can’t seem to understand why I’m confused, then I’ll explain some background. Before my Go phase, I was trying to get back into writing C. And I had a few head scrat…

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help