Home Backend Development Golang Baby steps with Go

Baby steps with Go

Aug 05, 2024 pm 07:28 PM

Baby steps with Go

I decided to give Go a try on my journey to pick up a new language that would be useful to my career and interests. This time I've been having a go at Go. I think as first impressions go, it's pretty nice.

This is not a guided tour, and arguably, not written for anyone else other than myself, as some personal reminders.

I gave myself a small project for it called Os-Release-Q . My intention was to be able to have a binary on any system I manage, such that I can print out exactly the information I need, without needing to parse or eye-grep for it.

First hurdle : import

Searching the web talks a lot about importing other people's packages , but very little about organising one's own code. Even the docs focus on go get rather than separation of concerns.

I encounter this hurdle quite a bit in every language, as each has its own idiosyncratic philosophy on how to go about it, and what limitations each has or imposes.

Of all the activities I undertook in learning the basics, coming from a predominantly python background, splitting my code into multiple files was what took me the longest to get answers to. In summary, I found the following:

  • top level needs a go.mod declaring module module-name
  • I can then set a src/ directory at top level, and a src/main.go in which to place my main function , with a package main declaration at the top
  • putting code in other files is a simple as creating a file like src/others.go with a package main declaration.
  • All functions and variables become available directly in any other file of package main , but the files need to be explicitly stated on the go build FILES call

For local submodules, the submodule must reside in a folder. It can declare a package submodule-name .

Say it is in src/submod/, with main implementor in src/submod/submod.go. In main.go we do import "module-name/src/submod" (with module-name pulled from go.mod). And then we can call submod.SomeFunction().

We note that submodule functions are only available to importers if their name starts with a Capitalised letter. So no doing submod.myFunction() - it has to be submod.MyFunction().

There are surely other considerations around submodules and imports, but as far as keeping code organised and segregated, this is the essentials.

To keep things sane, I tempted to only have one file declaring package main, and isolating the rest into submodules - these get imported automatically without needing to be declared in the go build FILES list of files.

Doing basic tasks

After I had resolved this specificity of Go, the rest fell in to place quite easily. For every basic task there was of course a StackOverflow entry, or a GoByExample.com page, and more basically, the Go language reference.

  • String handling is done via the strings package
  • Array handling has a number of native functions, of which the base_array = append(base_array, item1, item2) pattern - it also works for extending an array with the values of another via append(base, other_array...)
  • Error handling is done by passing out error objects typically, but not necessarily.
  • a "log" lib exists for a handy pre-configured no-faffing log. It includes a log.Fatal(message) call which logs an error, as well as immediately exiting.
  • Calling subprocesses is easy via the "os/exec" library, using exec.Command(base, args...) pattern

Two particularly common tasks deserve their own paragraphs.

Error handling

Basic error handling is often commented as being cumbersome, literally needing to handle errors in the midst of control flow. This may be anathema to programmers coming from a try/catch workflow, but handling the issue at the point where it can happen isn't so bad.

// explicit return item `err` forces us to be aware of it
// but having the ability to check it in the same breath is not so bad
if result, err := someCall(); err != nil {
    log.Fatal("Sorry.")
}

// Equally valid is
/*
result, err := someCall()
if err != nil {
    log.Fatal("Sorry")
}
*/

fmt.Println(result)
Copy after login

Compare try/catch way

try:
    result = someCall()
    print(result)
except:
    print("Sorry") # a little divorced from potential origin of error
    sys.exit(1)

Copy after login

Argument Parsing

I can't help but feel that the implementation of the flags library is a bit half-baked. Evidently people are used to and OK with it, given its survival in its current form.

Calling program -flag arg1 arg2 gives us the toggle that flag is set up to do, and positionals := flags.Args() returns us the array of ["arg1", "arg2"]

However calling program arg1 arg2 -flag does not toggle whatever -flags is supposed to do, and instead gives is positionals as ["arg1", "arg2", "-flag"] wherein the flag was not parsed.

This may be useful for passing in a sub-call like program colorize ls -l where the ls -l is passed down literally - so I can see a use case.

It's just that most programs out there allow flag arguments anywhere around positional items. ls dir1/ -l dir2/ is the same as ls -l dir1/ dir2/, and this is a convention that holds on the vast majority of Unix and Linux commands.

It may be just that this is something to get used to - and worth calling out.

Purpose and use case of Go

The file import paradigm aside, I found it pretty easy to get my basic application implemented. Anything I did wrong felt fairly obvious and the errors were meaningful. It really does feel like I can just focus on "getting things done."

From my very meagre amount of use so far, and taking my specific needs into account, I can see

  • easy to get started
  • compiled binary, no runtime dependency
  • simple language with types is a step up from shell scripting
  • allegedly easy multiprocessing support

I thought having sparse types instead of objects and inheritance would be a hinderance, but so far so good. I get by without them in other languages, so I suppose when I do get around to defining interfaces and types, it will feel like a step up from Lua and bash. I hope.

One of the reasons I wanted to explore a compiled-to-native language was to be able to produce binaries that could easily be shunted around, without needing to rely on a particular version of a runtime being present.

A colleague recently walked up to my desk in dismay, trying to solve getting Java 17 onto an old Node base image which was based on Debian 10 . Either he'd have to upgrade the Node version to get a newer base image, use a new Debian base image and install and configure Node manually, or scour the internet for a custom repo hosted by goodness-knows-who for a goodness-knows-if-hacked Java 17 that would run on Debian 10.

How much easier if the deployed software had no such conflicting runtime dependencies...

From an ops point of view, the one big gain I am feeling I would stand to feel is: I can easily write code, and build an ELF binary to then deploy on "arbitrary system X" and not have to contend with ensuring the right version of a given runtime is in place, and managing conflicting dependencies.

I'm sure there are other benefits, and I have heard a great deal said about the ease of use of multithreading and multiprocessing in Go, and I do intend on cooking up a mini project to explore that as a next step - probably something that might listen for inputs on multiple channels, and perform some basic tasks in response. I have had a use-case for that in some test automation tasks I've had before, so it's not alien to me at this point.

The above is the detailed content of Baby steps with Go. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles