TagMethods

Structs and Interfaces in Go

Thus far we have looked at many of the different data types that Go comes with. While you might be able to get away with making any program using only these types; it would be extremely tedious and difficult. Certain programs reuse data shapes over and over again. Therefore, creating a custom data type will ultimately save tons of time. In this post, we will be looking at Structs and Interfaces in Go.

Structs in Go

Structs are basically a custom data type that contains a set of named fields. In a struct, each field or variable has a type and like with functions we can define multiple fields that share the same type. Consider a Person struct.

structOur Person struct contains a name, gender, and age. Above, you can see the different ways that we can use the custom type that we created with this struct. When we use the new keyword to define a variable of our type struct, we allocate memory for the fields, set each of the fields to their zero values and return a pointer (*Person). We can access fields later in the code using the dot (.) syntax.

Methods in Go

Methods are special functions that we can associate to our structs in Go. We use a special type of syntax to do this. Consider for a moment the creation of a function that prints out our instance of the person struct.

Notice that we are passing the function parameters before the name of the function in this case. This is called using a receiver. The receiver is what allows us to associate this method to the struct Person. It also allows us to call the method with the dot syntax. This type of coding is much easier to read and it allows us to ignore using the & operator. Go will automatically pass a pointer to this function.

Because the function is associated to our struct of person, we can name it something simple. Lets try creating a different type of struct.

In this example, we created a type for a square. We then created a method to calculate the area of the square and then printed that result in our main function. We can also create embedded types using structs. For example, if we wanted to extend our person struct and add a few more fields we could do so.

Notice that we are able to bind our Person struct to a field inside of our Animal struct. We can also just say that it includes person rather then adding a new field to the Animal struct. When we add the struct the second way, we can just access that field by using the type directly with the dot syntax. For example, say a is a new animal type variable, a.Person.name = "Jazzpurr" is how we would assign the field with this syntax. Also, notice that when we embed structs into other structs they inherent the methods as well.

go-methodsInterfaces in Go

Say we have multiple shape structs inside of our program and they all have methods for their areas and parameters. We can further abstract these shape methods and assign them to an interface.

In this example, we have two method names and their return value types. We define an interface in a way that is similar to a struct. However, instead of defining fields inside of the interface, we define a list of methods. These methods are methods that must be contained in a type for that type to be a part of the interface. This interface might not seem very useful, however, we can use it as an argument for a function, a field for a struct, or even to create a struct out of the interface type.
Lets look at an example of these different implementations.

In this example, we created two structs one for rectangles and one for squares. We create an interface of shapes with the area methods inside of it. We use that shape interface to create a sum of areas method. This actually makes our interface behave like a struct in that it allows us to classify a shape as a shape, though not formally. We can then calculate the area of the square and the rectangle inside of the main function and print them out. Keep in mind that this example isn’t the best use of interfaces in Go. It merely shows the types of relationships that we can create between structs, interfaces and methods in Go.

Conclusion

In this post, we looked at both Structs and Interfaces in Go. We also looked at methods and we talked about fields. In our next posts, we will start to look at go-routines and how go handles concurrency and multi threading.  

Object Constructors in JavaScript

Today, we are going to take a more direct look at objects. Our first encounter with objects introduced us to their properties and methods. We looked at two specific ways of creating objects, the use of object literal notation and the new Object() function. In this post, we are going to look at object constructors.

Factories for Objects

Object ConstructorsWhen you define an object using the object literal notation you are defining a specific object instance. To leverage the power of objects as a data type, we need a way to streamline the creation of specific types of objects. Our original object example was that of a Person object. This was a good example for that lesson, however, it only works well for describing one specific person. What if we want to create a data type that can be applied to many different people? This is where object constructors become relevant.

Object constructors work like factories. They allow the programmer to create a function which will output multiple objects with the same general data shape.

In this example, we created a Person object constructor which takes three parameters. We assign these parameters to variables inside of the function which then allows us to create multiple instances of this object with different arguments being passed. If you call one of the three instance variables, you see a return of a Person object with the specified values. But then, what is that weird this keyword?

What The Hell Is this?!?

this keywordBefore we go any further, we need to talk about the this keyword. As you can see in the constructor above, we are using the this keyword three times in the variable assignments. What the this keyword allows us to do is to refer to the Person object directly even though it hasn’t been created. We are essentially saying that the Person function and object owns the firstName variable, the lastName variable, and the age variable. It allows us to differentiate the variables owned by the object from the parameters being passed into the function. this is basically a reference to the object itself. Here is a more general object constructor function.

The Car object constructor in this example uses different variable names for the parameters and the function attributes. Also, when you make a new instance of the Car object, you automatically get the object returned to the console. The this keyword might seem a little abstract at first but as you use it more you will get used to it.

Naturally, we can also create constructors that have methods inside of them. Look at this augmented Person object constructor.

In this example, we can call the greeting() function on any of the instance objects that we create with the new Person constructor using dot syntax. Calling the greeting() function will fire the anonymous function which was declared in the constructor.

Natural Constructor Functions in JavaScript

JavaScript also has it’s own native object constructors. Below is a chart with some of the different built-in JavaScript object constructors. Some are very straightforward and others we have already talked about. There are also a few that we have yet to talk about.

Object Constructors - Mind FuckWe’ve alluded to this many times before but most items inside of JavaScript are Objects and almost everything inside of JavaScript is treated as an Object in some way. The larger exceptions to this rule are the primitive types like numbers and strings. As a result, JavaScript still treats primitive types in a similar fashion to objects even if they aren’t objects themselves.

new Array();Creates an Array Object
new String();Creates a String Object
new Number();Creates a Number Object
new Boolean();Creates a Boolean Object
new Object();Creates an Object Object
new Date();Creates a Date Object
new Function();Creates a Function Object
new RegExp();Creates a new Regular expression Object

Closing

In this post, we introduced the concept of Object constructors in JavaScript. We showed a few examples of Object constructor functions and talked about the this keyword. Our next post will delve deeper into the world of objects as we look at prototypes and getter and setter functions.

Manipulating Strings with String Methods

Thus far in our adventure through JavaScript, we have talked about the different types of data that you can use. We have also looked at functions and objects as well as control flow. In this post, we are going to look a little deeper at strings in JavaScript. Specifically, we are going to take a look at the different functions or methods that we can use on strings.

Something that we’ve neglected to mention up until now, but have more or less implied, is that JavaScript treats it’s primitive data types like Objects. This is why numbers and strings have methods and properties like any other object in JavaScript.

Treating Strings as Objects

4645356096_927c5c0e8c_zIn this example, we declared a string variable, “string object” and we ran three string methods on it. The length method returns the length of a string similar to the length method for an array. The search method allows us to query for characters or strings within the original string. If you try searching for something not inside the string you will get a return value of -1 instead. The ToUpperCase method returns a copy of the string with all of the characters as uppercase letters. In many cases, you will use these methods to either manipulate a string for consistency in a program or to verify what is inside of a string that is being passed through input.

Here we introduce two more methods, the replace method and the toLowerCase method. The toLowerCase method is like the toUpperCase method but it converts all of the characters to lowercase rather than uppercase. The replace method allows us to replace parts of the string with other strings. It takes two parameters, the initial part we want to replace and the item we are replacing it with. Note, you can also use an empty string as a replacement. We can also do something like this:

Intro to RegEx and Slicing

As you can see in the example above, we used the escape character backslash and the character g (global) to indicate that we wanted to replace all of the spaces. This type of syntax is what is called a regular expression or regex. With this simple regex, we can find patterns in our strings and globally replace them. We can also use regex inside of the search method to just find the patterns. (we will talk about regex more later.)

picture2-substring-java-string-diagramWe can also chop strings to pieces using the substr(), substring() and slice() methods. The slice method removes anything outside of the indexes that we specify. Substring() is a much older method that does the same thing as slice() but can not accept negative indexes. Substr() allows us to separate a string in a slightly different way from the slice method, with the second parameter being the length of the extracted string. Below are examples of each.

There is one more feature of strings that we should cover before closing out this post and that is how we can access them as arrays as well as convert them to arrays. Be careful when you try to access a string as an array before converting it because it can throw all kinds of awful errors.  It’s unsafe and unpredictable and doesn’t work in all browsers so for the most part, it is something you should avoid. You can, however, use the split() method to convert a string to an array and then access that array like any other array. The split string method will split the string into an array of strings at the character type you indicate. If you don’t pass anything onto split it’ll just convert the entire string to an array of index one. The string will just be on the first index which is not that useful.

Closing

In this post, we talked about the different string methods that you have access to in JavaScript.  We talked about how JavaScript naturally treats primitive types as objects and how we can manipulate strings with the built-in string methods.  We also looked at converting strings to arrays and splicing strings into parts.

In our next post, we will look at the common number methods that are used in JavaScript. We will also start to build small programs. For this, we will need a more standard environment to develop our JavaScript in. We will go over how to install node.js and the text editor of your choice.