From C++ to Golang: A Software Engineer's Journey to Expanding the Toolkit ??

From C++ to Golang: A Software Engineer's Journey to Expanding the Toolkit ??

The Spark ??

Two years ago, while on a coding hiatus during a vacation, I chanced upon Golang. Recognizing its burgeoning presence in the tech landscape, I was intrigued. Merely a week with "A Tour of Go", and I was smitten. The clarity and fluidity of Golang resonated deeply with me.

Upgrading My Skills ??

To deepen my understanding, I successfully completed the "Programming with Google Go" specialization on Coursera. I earned a certificate of completion, which was not only a formal recognition of my learning but also a tremendously fulfilling experience.

The Shift in Action: A Hypothetical Case Study ??

Let's delve into a familiar task: processing large JSON payloads. In C++, managing this often requires integrating external libraries and meticulous memory handling. Golang, on the other hand, boasts native support for JSON marshaling and unmarshaling. But the elegance lies in how Go moves much of the unmarshaling logic from the implementation function to the struct declaration itself.

?? C++ JSON Processing Example

#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    json complexObj = {
        {"name", "John"},
        {"age", 30},
        {"address", {
            {"city", "New York"},
            {"zipcode", "10001"}
        }}
    };

    std::string serializedObj = complexObj.dump();
    std::cout << "Serialized JSON: " << serializedObj << std::endl;

    json deserializedObj = json::parse(serializedObj);

    std::string name = deserializedObj["name"];
    int age = deserializedObj["age"];
    std::string city = deserializedObj["address"]["city"];
    std::string zipcode = deserializedObj["address"]["zipcode"];
    
    std::cout << "Name: " << name << ", Age: " << age << ", City: " << city << ", Zip: " << zipcode << std::endl;

    return 0;
}        

In C++, the focus is primarily on the main implementation, and the external library nlohmann/json.hpp assists in the serialization and deserialization.

?? Golang JSON Processing Example

package main

import (
	"encoding/json"
	"fmt"
)

type Address struct {
	City    string `json:"city"`
	Zipcode string `json:"zipcode"`
}

type ComplexObj struct {
	Name    string  `json:"name"`
	Age     int     `json:"age"`
	Address Address `json:"address"`
}

func main() {
	jsonStr := `{
		"name": "John",
		"age": 30,
		"address": {
			"city": "New York",
			"zipcode": "10001"
		}
	}`

	var obj ComplexObj
	if err := json.Unmarshal([]byte(jsonStr), &obj); err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Printf("Name: %s, Age: %d, City: %s, Zip: %s\n", obj.Name, obj.Age, obj.Address.City, obj.Address.Zipcode)
}        

With Golang, the struct definitions with their specific field tags elegantly shift a significant portion of the parsing logic. Instead of handling the intricacies in the main function, Go allows us to define the structure and its relationship with the JSON data right within the struct declaration. This nuance exemplifies one of the many refreshing changes I encountered in my transition to Go.

The Advantages ??

  • Simplicity: If you're familiar with C++, picking up Golang can take as little as two weeks.
  • Development Speed: Features like auto-formatting and a rich set of libraries lead to faster development cycles.
  • Concurrency: Go's goroutines make handling parallel tasks incredibly efficient.
  • Community Support: A thriving community translates into better support, an abundance of libraries, and shared wisdom.

The Challenges and Overcoming Them ??

Initially, my mindset was firmly rooted in the object-oriented paradigms of C++. Transitioning to Golang was a bit challenging because I was accustomed to classic OOP features like encapsulation and polymorphism. It's worth noting that while Golang is influenced by OOP concepts, it isn't purely an object-oriented language. Instead, it adopts a unique approach that merges procedural and concurrent programming paradigms.

For instance, while Golang doesn't support classes in the traditional sense, it does offer a powerful and flexible type system with "structs" and "interfaces." This system allows us to achieve behavior similar to OOP. The absence of classes and inheritance is often pointed out, but Golang provides functional alternatives. For example, encapsulation can still be achieved using packages, and interfaces can be leveraged for polymorphic behavior.

This different paradigm took some time to grasp, but once I adjusted my perspective, I found it to be efficient and intuitive in many scenarios.

A Balanced View ??

While Golang is excellent for building scalable and efficient microservices, C++ still holds its ground, especially in projects that require fine-grained control over system resources. The key is to choose the right tool for the job.

The Business Upside ??

For organizations, adopting Golang can be a game-changer. The speed and efficiency Golang offers can significantly reduce development time, enabling faster product launches.

Looking Ahead ??

As microservices continue to dominate the architectural landscape, the demand for languages designed with scalability and simplicity in mind will only grow. In this context, Golang seems poised for a bright future.

Conclusion ??

My transition from C++ to Golang has been a truly enlightening experience. It's not about abandoning one for the other; it's about having more tools in your toolkit. Golang is a powerful addition that offers a different set of advantages, making the programmer's life easier in many ways.


Final Words

So, what are your thoughts on this transition? Whether you're a developer or an executive, I'd love to hear your thoughts. Have you considered making a similar move? Let's discuss!

Alexander Sopov

Lead C++ Developer/Team Lead

1 年

So, based on this example, the main advantage of one is that JSON serialisation (very specific and niche task) is an integral part of a language and so slightly easy to use than some weird 3rd party library for another one.

回复
Jonathan O'Connor

Software Developer, Chess Coach, Streamer

1 年

Iheb, As is usual with language comparisons, it is very difficult to do a fair comparison. For example, the C++ could be rewritten using the recommended nlohmann code thus: https://godbolt.org/z/h83b3T3qd As you can see it does what the golang version does with one extra line per struct to define the mapping between struct members and JSON field names. The only down side to this solution is that any errors in the JSON will throw exceptions. In my current job, I am trying to come up with a nice way to get a list of errors during JSON parsing, but I believe it will be as easy as the use of the macros seen in my example. For me the big positive for golang is the concurrency model, using actors and message passing. The downside with golang is the extra boilerplate code that often needs to be written. For some people that's an advantage, but it would seem that from studies, the higher level we can write code in, the more productive people are. I like all the abstraction mechanisms available in C++ code. If I had reflection, then I'd be very happy.

Stanislav Frolov

I don't speak on behalf of my employer. Nor do they.

1 年

Golang is truly corporate language. It’s strict and it provides a rich standard library and toolchain. Both facts help to scale software development to teamwork. While C++ engineers argue about libraries to use, the code style, project structure, build system, and other very important things, a team that uses Go just delivers the product. The sad downside of it is that the code loses personality of its authors because you know in C++ you can express ideas in one of infinite ways, in very **your** manner. I intentionally skipped technical pros and cons of both languages because they all are just boring. I personally find a use of both languages in my professional and private life. C++ is much more fun to write the code, golang is funnier to deliver a solution.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了