func foo() *string {} // returns a pointer to a string
Use the & operator to get the pointer of a value/struct.
var v int = 100// we got a pointer to the value of v, also pt1 is of type pointer to intvar pt1 *int = &v
Use the * operator again, to “use” a pointer. When *someVariable is used, we’re modifying the underlying value by reference. If you don’t use the *, you update the pointer itself.
var v int = 100var pt1 *int = &v// Updating the value using *pt1*pt1 = 200fmt.Println("The updated value of variable v is =", v)// Updating the pointer itselfvar newV int = 300pt1 = &newVfmt.Println("The new value pt1 points to is =", *pt1)
Golang is a mostly procedural language, however it adopts certain OOP-like features (as well as FP-like features). Golang Methods are a perfect example.
Take these two functions
type Post struct { ... }func UpdatePost(post *Post) { // Function A post.title = "new Title"}func (post *Post) UpdatePost() { // Function B post.title = "new Title"}
Function A is a function and is called with UpdatePost(post), meanwhile Function B is a method and is called with post.UpdatePost(). Its important to note, that Function B is just syntax sugar. When compiled, both output the same binary.
This is pretty magical IMO. Especially when comparing to javascript, where to achieve the same thing, you’d need to either have a helper inside the post instance or post be a class. Now image you want an array of Posts, in js you’d have to create a new instance of the Post class/object. Meanwhile, in go, no need!
Btw, the post in func (post *Post) UpdatePost(){} is called a receiver argument.
All files within the same folder must have the same package name. In the main directory where the go.mod file can be found, that package is main. If you want to e.g. make a utils file, with its own package, it needs to be in a folder.
Import and export is done via casing. e.g.
func isNotExported() {}// vsfunc IsExported() {}
Coming from js, where you can do anything (good and bad!), these limitations at first were annoying but I actually quite like them. Every codebase will operate the same and its overall simple.
Though being able to simply grep for export in a file, would have been nice.
As I learn Golang and find its syntax and standard library really nice, I wondered if I could use it for scripting. Bash scripts get me pretty far, but since I’m a big fan of the Fish Shell, I’d like a shell or even OS agnostic tool. Sure, I could use python. But I don’t like python as much.
Of course, every system has some version of python installed by default, but that’s also true for bash and curl. And if need be, I can just compile and publish some binaries to GitHub.
The above script works splendidly. Its not quite a shebang, but it works the same way.
The following will makes templ files get treated as HTML files as far as tailwind/emmet is concerned. This should make templ files have all the conveniences you’d expect and that you’re probably used to when writing JSX.