Skip to content

Instantly share code, notes, and snippets.

@zah
Created September 21, 2011 14:05
Show Gist options
  • Select an option

  • Save zah/1232112 to your computer and use it in GitHub Desktop.

Select an option

Save zah/1232112 to your computer and use it in GitHub Desktop.
Forwarding references
type Connection = object
userName: string
messageHistory: list[string]
type ConnectionManager = object
networkConnections: map[string, Connection]
const
NULL_CONNECTION : Connection = ...
# The Connection values could not be really copied. Maybe, I should use just var here?
proc getConnection(m: var ConnectionManager, host: string): Connection =
return m.networkConnections[host]
# If I use the NullObject pattern, returning var type becomes harder?
proc getUserConnection(m: var ConnectionManager, user: string): Connection =
for host, con in items(networkConnections)
if con.userName == user
return con
return NULL_CONNECTION
var gConnectionManager : ConnectionManager
# Let's assume that the list of messages is expensive to copy and we don't want to do it
proc getUserMessages(user: string) : list[string] =
gConnectionManager.getUserConnection(user).messageHistory
# Multiple bodies of the function are compiled for the two usage patterns?
let messages1 = getUserMessages("Araq")
# just passes the reference
var messages2 = getUserMessages("Araq")
# creates/initializes a copy
# or a copy is created by the returned reference?
proc getUserName(host: string) : string =
gConnectionManager.getConnection(host).nameName
proc getMostActiveUser(): string =
var mostActiveHost = "foo" & "bar" & baz # this a temporary created local string
return getUserName(mostActiveHost)
# This can not be safely optimized with the crude rules
# mostActiveHost in the body of getMostActiveUser is a temporary varialbe
# passed to a function that could return it (so, reference could not be forwarded)
let user = getMostActiveUser()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment