This question already has answers here:
What is this "err.(*exec.ExitError)" thing in Go code? [duplicate]
(2 answers)
What is the meaning of "dot parenthesis" syntax? [duplicate]
(1 answer)
Closed 5 years ago.
Go Newb here -- I've encountered the following bit of Go code that I didn't write
if tc, ok := tng.(ThingClasser); ok {
//... do some stuff ...
}
I won't understand the semantics of tng.(ThingClasser).
In some ways this looks like a method call -- i.e. there are two variables (ec, ok) sitting there ready to accept multiple return values.
However, tng.(ThingClasser) itself looks like its a property access, not a method call.
However however, the parens around ThingClasser are a wrinkle I've never seen before. Also, if it matters, the ThingClasser symbol is defined elsewhere in this project as an interface, so I think maybe this is some syntactic sugar around an does this implement an interface -- but then the two return values confused me.
Googling hasn't turned up anything concrete, but this is one of those hard things to google for.
Does anyone here know what this call/syntax is in GoLang, and possible point me at the relevant manual pages so I can RTFM?
It's a type assertion. The returned values are 1) the object, converted to the given type; and 2) a boolean indicating if the conversion was successful. ThingClasser is the type being converted to. Documentation can be found here: https://golang.org/ref/spec#Type_assertions
This question already has answers here:
What does <<-CONSTANT do?
(3 answers)
Closed 6 years ago.
Just found this piece of code in a Google Ruby API client on Github.
NOT_FOUND_ERROR = <<END
Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials
for more information
END
I never saw it and tested it in the console:
>> NOT_FOUND_ERROR = <<END
blabla
END
=> "blabla\n"
So basically it is a weird way to create a string? What's the motivation for using this syntax rather than NOT_FOUND_ERROR = "blabla\n" ?
EDIT: As this question was marked with "possible duplicate" I want to explain why it is not just a dup. The question that is a possible duplicate simply asks what a certain ruby script does. This Ruby script also includes the <<ABC syntax and this obviously is the core of the question, but it is not really helpful because it is hard to find. Besides that, I am going further and ask for the motivation to use this notation over creating a normal string.
It is HEREDOC. You can read more about it here(wiki) and here(Ruby instances). Usually heredocs used for more readability of multiline text.
This question already has answers here:
How to understand symbols in Ruby
(11 answers)
Using Ruby Symbols
(5 answers)
Closed 8 years ago.
I'm not clear on the value and proper use of symbols.
The benefit seems to be that they remove the need for multiple copies of the same hash by letting it exist only in memory. I wonder whether this is true and what other benefits this brings.
If I were creating a user object with properties such as name, email, and password, and used symbols for each property instead of strings, does that mean that there is only one object for each property? It seems like this would avoid a string copy for the properties in the hash (which seems like a good thing).
Can someone help me understand what a symbol is and when it's better to use one over a string in a hash? What are the benefits and pitfalls of each?
Also, can anyone speak to the memory tradeoffs of each? With scalability being important, I'm curious if symbols would help with speed.
Symbols, or "internals" as they're also referred to as, are useful for hash keys, common arguments, and other places where the overhead of having many, many duplicate strings with the same value is inefficient.
For example:
params[:name]
my_function(with: { arguments: [ ... ] })
record.state = :completed
These are generally preferable to strings because they will be repeated frequently.
The most common uses are:
Hash keys
Arguments to methods
Option flags or enum-type property values
It's better to use strings when handling user data of an unknown composition. Unlike strings which can be garbage collected, symbols are permanent. Converting arbitrary user data to symbols may fill up the symbol table with junk and possibly crash your application if someone's being malicious.
For example:
user_data = JSON.load(...).symbolize_keys
This would allow an attacker to create JSON data with intentionally long, randomized names that, in time, would bloat your process with all kinds of useless junk.
Besides avoiding the need for repeated memory allocation, symbols can be compared for equality faster than strings, and their hash codes can be computed faster than strings (so both storing and retrieving data from a Hash will be faster when symbol rather than string keys are used).
Internally, Ruby uses something closely related to symbols to identify methods, the names of classes, and so on. So, for example, when you retrieve a list of the methods an object supports (with obj.methods), you get back an array of symbols. When you want to call a method "dynamically", using a name stored in a variable or passed in as an argument, you must use a symbol. Likewise for getting/setting the values of instance variables, constants, and so on.
Intuitively, you can think of it this way. If you've ever programmed in C, you have written things like:
#define SOMETHING 1
#define SOMETHING_ELSE 2
These defines eliminate the need to use "magic numbers" in your code. The names used (SOMETHING, etc) are not relevant to users of your program, just as the names of functions or classes are not relevant to users. They are just "labels" which are internal to the code, and are of concern only to the programmer. Symbols play a similar role in Ruby programs. They are a data type with performance properties similar to integers, but with a literal syntax which makes them appear as meaningful names to a human programmer.
Once you "get" the concept of Ruby symbols, understanding Lisp symbols will be much easier, if you ever program in Lisp. In Lisp, symbols are the basic data type which program code is composed of. (Because Lisp programs are data, and can be manipulated as such.)
You should think about symbols like a numbers. It is constant, immutable and non-gc object that is created on first usage and you should use them whenever you need to reference to object that cannot be duplicated, like:
messages aka methods (Ruby doesn't have overloading)
hash keys (Ruby doesn't have multi hashes)
Yes, your example is fine.
name, email, and password could all be stored as symbols, even in a hash - the specific object could still be a string object.
{
:name => 'John doe',
:email => 'foo#hotmail.com',
:password => 'lassdgjkl23853'
}
HAML code usually uses symbols, like this:
%meta{:http_equiv=>"Content-Type", :content=>"text/html; charset=utf-8"}
But why isn't it like this, using strings instead?
%meta{"http_equiv"=>"Content-Type", "content"=>"text/html; charset=utf-8"}
Both work fine.
What real benefit do HAML programmers see in using symbols instead of strings? I don't get it. My guess is that HAML just parses the string from the symbol anyway, so what's the point?
The structure you are referring to here: {:http_equiv=>"Content-Type", :content=>"text/html; charset=utf-8"} is a Hash. Here are some very good answers to the question "Why does Ruby use symbols as keys in Hashes?"
Why use symbols as hash keys in Ruby?
the structures you're referencing there are maps, and the ruby standard is to use symbols as keys rather than strings.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ruby syntax question: Rational(a, b) and Rational.new!(a, b)
I'm in the process of reading the ruby pickaxe book, and I'm confused about the syntax of creating rational numbers.
Rational(3,4) * Rational(1,2)
produces
=> 3/8
Why is the new method not needed for Rational (I also noticed for example I can create a string without the new method)?
For one thing, Ruby has no new keyword. new is a class method that all classes have (they inherit it from Class) that creates an object of that class. When you see something like Rational(3,4), Rational is really just a private method of Object (defined in Kernel) that makes creating rational numbers easier. For more on those constructor-methods, see this answer of mine: https://stackoverflow.com/a/9677125/1008938
It's a method that happens to have the same name as the class. It's a common conversion idiom in Ruby.