At XpresServers, we constantly strive to deliver total customer satisfaction with all our hosting services. That’s why we offer fast, reliable and secure service that’s backed by our friendly, knowledgeable support team, 24/7.

Methods

Introduction

Functions allow you to organize logic into repeatable procedures that can use different arguments each time they run. In the course of defining functions, you’ll often find that multiple functions might operate on the same piece of data each time. Go recognizes this pattern and allows you to define special functions, called methods, whose purpose is to operate on instances of some specific type, called a receiver. Adding methods to types allows you to communicate not only what the data is, but also how that data should be used.

Defining a Method

The syntax for defining a method is similar to the syntax for defining a function. The only difference is the addition of an extra parameter after the func keyword for specifying the receiver of the method. The receiver is a declaration of the type that you wish to define the method on. The following example defines a method on a struct type:

We created a struct called Creature with string fields for a Name and a Greeting. This Creature has a single method defined, Greet. Within the receiver declaration, we assigned the instance of Creature to the variable c so that we could refer to the fields of the Creature as we assemble the greeting message in fmt.Printf.

In other languages, the receiver of method invocations is typically referred to by a keyword (e.g. this or self). Go considers the receiver to be a variable like any other, so you’re free to name it whatever you like. The style preferred by the community for this parameter is a lower-case version of the first character of the receiver type. In this example, we used c because the receiver type was Creature.

Within the body of main, we created an instance of Creature and specified values for its Name and Greeting fields. We invoked the Greet method here by joining the name of the type and the name of the method with a . and supplying the instance of Creature as the first argument.

Go provides another, more convenient, way of calling methods on instances of a struct as shown in this example:

This example is identical to the previous one, but this time we have used dot notation to invoke the Greet method using the Creature stored in the sammy variable as the receiver. This is a shorthand notation for the function invocation in the first example. The standard library and the Go community prefers this style so much that you will rarely see the function invocation style shown earlier.

We’ve modified the earlier examples to introduce another method called SayGoodbye and also changed Greet to return a Creature so that we can invoke further methods on that instance. In the body of main we call the methods Greet and SayGoodbye on the sammy variable first using dot notation and then using the functional invocation style.

Both styles output the same results, but the example using dot notation is far more readable. The chain of dots also tells us the sequence in which methods will be invoked, where the functional style inverts this sequence. The addition of a parameter to the SayGoodbye call further obscures the order of method calls. The clarity of dot notation is the reason that it is the preferred style for invoking methods in Go, both in the standard library and among the third-party packages you will find throughout the Go ecosystem.

Defining methods on types, as opposed to defining functions that operate on some value, have other special significance to the Go programming language. Methods are the core concept behind interfaces.

Interfaces

When you define a method on any type in Go, that method is added to the type’s method set. The method set is the collection of functions associated with that type as methods and used by the Go compiler to determine whether some type can be assigned to a variable with an interface type. An interface type is a specification of methods used by the compiler to guarantee that a type provides implementations for those methods. Any type that has methods with the same name, same parameters, and same return values as those found in an interface’s definition are said to implement that interface and are allowed to be assigned to variables with that interface’s type. The following is the definition of the fmt.Stringer interface from the standard library:

type Stringer interface {
String() string
}

For a type to implement the fmt.Stringer interface, it needs to provide a String() method that returns a string. Implementing this interface will allow your type to be printed exactly as you wish (sometimes called “pretty-printed”) when you pass instances of your type to functions defined in the fmt package. The following example defines a type that implements this interface:

This example defines a new struct type called Ocean. Ocean is said to implement the fmt.Stringer interface because Ocean defines a method called String, which takes no parameters and returns a string. In main, we defined a new Ocean and passed it to a log function, which takes a string to print out first, followed by anything that implements fmt.Stringer. The Go compiler allows us to pass o here because Ocean implements all of the methods requested by fmt.Stringer. Within log, we use fmt.Println, which calls the String method of Ocean when it encounters a fmt.Stringer as one of its parameters.

If Ocean did not provide a String() method, Go would produce a compilation error, because the log method requests a fmt.Stringer as its argument. The error looks like this:

In the examples so far, we have defined methods on the value receiver. That is, if we use the functional invocation of methods, the first parameter, referring to the type the method was defined on, will be a value of that type, rather than a pointer. Consequently, any modifications we make to the instance provided to the method will be discarded when the method completes execution, because the value received is a copy of the data. It’s also possible to define methods on the pointer receiver to a type.

Pointer Receivers

The syntax for defining methods on the pointer receiver is nearly identical to defining methods on the value receiver. The difference is prefixing the name of the type in the receiver declaration with an asterisk (*). The following example defines a method on the pointer receiver to a type:

The S.S. DigitalOcean has the following occupants:
Sammy the Shark
Larry the Lobster

This example defined a Boat type with a Name and occupants. We want to force code in other packages to only add occupants with the AddOccupant method, so we’ve made the occupants field unexported by lowercasing the first letter of the field name. We also want to make sure that calling AddOccupant will cause the instance of Boat to be modified, which is why we defined AddOccupant on the pointer receiver. Pointers act as a reference to a specific instance of a type rather than a copy of that type. Knowing that AddOccupant will be invoked using a pointer to Boat guarantees that any modifications will persist.

Within main, we define a new variable, b, which will hold a pointer to a Boat (*Boat). We invoke the AddOccupant method twice on this instance to add two passengers. The Manifest method is defined on the Boat value, because in its definition, the receiver is specified as (b Boat). In main, we are still able to call Manifest because Go is able to automatically dereference the pointer to obtain the Boat value. b.Manifest() here is equivalent to (*b).Manifest().

Whether a method is defined on a pointer receiver or on a value receiver has important implications when trying to assign values to variables that are interface types.

Pointer Receivers and Interfaces

When you assign a value to a variable with an interface type, the Go compiler will examine the method set of the type being assigned to ensure that it has the methods the interface expects. The method sets for the pointer receiver and the value receiver are different because methods that receive a pointer can modify their receiver where those that receive a value cannot.

The following example demonstrates defining two methods: one on a type’s pointer receiver and on its value receiver. However, only the pointer receiver will be able to satisfy the interface also defined in this example:

This example defined an interface called Submersible that expects types having a Dive() method. We then defined a Shark type with a Name field and an isUnderwater method to keep track of the state of the Shark. We defined a Dive() method on the pointer receiver to Shark which modified isUnderwater to true. We also defined the String() method of the value receiver so that it could cleanly print the state of the Shark using fmt.Println by using the fmt.Stringer interface accepted by fmt.Println that we looked at earlier. We also used a function submerge that takes a Submersible parameter.

Using the Submersible interface rather than a *Shark allows the submerge function to depend only on the behavior provided by a type. This makes the submerge function more reusable because you wouldn’t have to write new submerge functions for a Submarine, a Whale, or any other future aquatic inhabitants we haven’t thought of yet. As long as they define a Dive() method, they can be used with the submerge function.

Within main we defined a variable s that is a pointer to a Shark and immediately printed s with fmt.Println. This shows the first part of the output, Sammy is on the surface. We passed s to submerge and then called fmt.Println again with s as its argument to see the second part of the output printed, Sammy is underwater.

If we changed s to be a Shark rather than a *Shark, the Go compiler would produce the error:

Output

cannot use s (type Shark) as type Submersible in argument to submerge:
Shark does not implement Submersible (Dive method has pointer receiver)

The Go compiler helpfully tells us that Shark does have a Dive method, it’s just defined on the pointer receiver. When you see this message in your own code, the fix is to pass a pointer to the interface type by using the & operator before the variable where the value type is assigned.

Conclusion

Declaring methods in Go is ultimately no different than defining functions that receive different types of variables. The same rules of working with pointers apply. Go provides some conveniences for this extremely common function definition and collects these into sets of methods that can be reasoned about by interface types. Using methods effectively will allow you to work with interfaces in your code to improve testability and leaves better organization behind for future readers of your code.

If you’d like to learn more about the Go programming language in general, check out our How To Code in Go series.

Publishing posts to your blog on a regular basis is essential. However, several issues might get in the way of consistent and optimized publishing, such as a full workload, trouble posting during high-traffic periods, or even the decision to take a vacation. Even expert bloggers need a little R ‘n R now and then.

Fortunately, if you built your website with WordPress, there are a number of ways you can schedule your posts for publication ahead of time. Scheduling your posts enables you to put fresh content up on your site at regular intervals — without having to actually log in each time.

In this article, we’ll explain the advantages of scheduling blog posts on your WordPress site. Then we’ll share a few methods for doing so, and go over some tips for troubleshooting issues that may arise during the process. Let’s dive in!

Why It’s Smart to Schedule Your Blog Posts

Creating a schedule for your blog posts is the best way to ensure that you always have fresh content. Plus, when you post regularly, readers will always know when to expect new articles. This can help keep them engaged and coming back regularly.

On top of that, scheduling posts can help you manage your workload. When you have a busy week coming up, you can write your posts ahead of time and set a future publication date and specific time for each. Scheduled posts can also make it possible for you to take a vacation from your blog.

In addition, assigning publication dates and times is useful for posting during peak traffic hours. Your readers may be most active on your site during a time of day you have to be away from your computer, for example. Automated publication lets you make new posts live at the ideal moment.

How to Schedule Posts in WordPress (3 Methods)

Fortunately, there are several ways to schedule posts on your WordPress website, so you can choose the method that works best for you. Let’s look at three of the most common options.

1. Schedule Posts in the Block Editor

WordPress has innate post scheduling capabilities, which you can access right from the editor screen. Let’s look at how to set a post up for automatic publication in the Block Editor (which you have access to if your WordPress version is 5.0 or higher).

Open up the post you want to schedule, and in the sidebar to the right, select the Document tab. Under Status & Visibility, you’ll see that your post is set to publish Immediately by default.

If you click the link, it will open a calendar where you can select a future date and time. Once you’ve done so, Immediately will change to your specified publication time in the sidebar. Click anywhere outside the calendar to close it.

When you’ve given your post one final read-through and are sure it’s ready to go, click on the blue Schedule button at the top of the editor.

You’ll have the chance to review and edit your post’s publication date and time and set its visibility status to Private, Public, or Password-Protected. WordPress will also point out any last-minute items you may want to address.

You should receive a notification that your post has been scheduled and see its changed status in the Publish widget.

If you need to make any updates, you can do so by clicking on the blue Edit link next to any of the settings. Be sure to hit the Update button afterward.

3. Use a Plugin to Schedule Posts

If you want to access more advanced automatic publishing features, you may want to consider WordPress plugins. Let’s look at two of the best options.

WP Scheduled Posts

WP Scheduled Posts adds an editorial calendar to your WordPress dashboard. You can drag and drop posts to schedule them so setting publication dates is fast and easy. This tool also helps you keep track of all your authors if you have multiple people creating content.

You can even add new posts right in the calendar — save those great ideas you have for a future date. The plugin is free to download, but if you opt for a premium plan, you’ll gain access to additional features including the ‘Auto Scheduler’ and ‘Missed Post Handler.’

CoSchedule

If you need a more complete content and marketing scheduling system, check out CoSchedule. While you’ll still have to follow the steps for scheduling posts in the WordPress editor as described above, with CoSchedule, you can manage your scheduled blog posts, social media content, and marketing campaigns from a single calendar right in your WordPress dashboard.

You can download the CoSchedule WordPress plugin for free, but you won’t be able to do anything with it unless you also have a paid CoSchedule account. Plans for those accounts start at $80 per month.

Troubleshooting Issues With WordPress Scheduled Posts

Scheduling posts in WordPress is simple, but there are a few issues you may run into. Fortunately, the most common problems have easy solutions.

Setting the Right Timezone

First, it’s important to make sure that when you’ve chosen a publication date and time, they’re set to the right time zone.

You can check your site’s time zone settings by going to Settings > General in your WordPress dashboard, and scrolling down to Timezone. There, you can see the time zone your site is currently set to, and change it if need be.

Handling Missed Posts

You’ll also want a failsafe in case something goes wrong, and a post you’ve slated for publication doesn’t go live as expected. For this, we suggest looking into a plugin such as Scheduled Post Trigger, which checks for and publishes missed scheduled posts.

This way, if your post doesn’t publish automatically for whatever reason, the plugin can still get your content up on your site (even if it’s a little late). If you’re using the premium version of WP Scheduled Posts, its ‘Missed Posts Handler’ feature works in much the same way.

Unscheduling Posts

Finally, there may be times when you’ve set up a post for future publication, and then you decide you want to publish it right away instead. To do this in the Classic Editor, head over to the Publish widget and click on Edit next to the date by Scheduled for. Change the settings to the current date and time, and then select OK.

Click on the blue button, which will say either Update or Publish. Once you do, you should receive a notification that your post has been published.

In the Block Editor, this functionality works much the same. Change the scheduled date and time to the current moment, and click outside the calendar to exit the feature. The blue button at the top of the editor will now say Publish.

Select it, and WordPress will put the post up on your site immediately.

Keep Us Posted

Posting consistently on your WordPress blog is key to your site’s success. Scheduling your blog posts in advance can help you gain more loyal followers, while also making it easier for you to manage your site over time.

Do you have any questions about how to schedule posts in WordPress? Follow us on Twitter and let us know!

Introduction

Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

All objects in JavaScript descend from the parent Object constructor. Object has many useful built-in methods we can use and access to make working with individual objects straightforward. Unlike Array prototype methods like sort() and reverse() that are used on the array instance, Object methods are used directly on the Object constructor, and use the object instance as a parameter. This is known as a static method.

This tutorial will go over important built-in object methods, with each section below dealing with a specific method and providing an example of use.

Prerequisites

In order to get the most out of this tutorial, you should be familiar with creating, modifying, and working with objects, which you can review in the “Understanding Objects in JavaScript” article.

For additional guidance on JavaScript in general, you can review our How To Code in JavaScript series.

Object.create()

The Object.create() method is used to create a new object and link it to the prototype of an existing object.

We can create a job object instance, and extend it to a more specific object.

The barista object now has one property — position — but all the other properties and methods from job are available through the prototype. Object.create() is useful for keeping code DRY by minimizing duplication.

In the example above, we tried to override the password hunter2 with *******, but the password property remained the same. We also tried to add a new property, active, but it was not added.

Object.isFrozen() is available to determine whether an object has been frozen or not, and returns a Boolean.

Object.seal()

Object.seal() prevents new properties from being added to an object, but allows the modification of existing properties. This method is similar to Object.freeze(). Refresh your console before implementing the code below to avoid an error.

We can see in the output that the prototype of the employees array has access to pop, find, and other Array prototype methods. We can confirm this by testing the employees prototype against Array.prototype.

Object.getPrototypeOf(employees) === Array.prototype;

Output

true

This method can be useful to get more information about an object or ensure it has access to the prototype of another object.

There is also a related Object.setPrototypeOf() method that will add one prototype to another object. It is recommended that you use Object.create() instead as it is faster and more performant.

Conclusion

Objects have many useful methods that help us modify, protect, and iterate through them. In this tutorial, we reviewed how to create and assign new objects, iterate through the keys and/or values of an object, and freeze or seal an object.

If you need to review JavaScript objects you can read “Understanding Objects in JavaScript.” If you would like to familiarize yourself with the prototype chain, you can take a look at “Understanding Prototypes and Inheritance in JavaScript.”