Linux mint install golang

How to Install Go on Linux Mint 20?

Go is an open-source and modern programming language that is used to build efficient and reliable software. Since it is a compiled language, therefore, we can easily compile it on any platform and create an executable file.

Go can be installed on Linux Mint 20 from the base repository and the Go tarball.

Installing Go on Linux Mint 20 from the Standard Repositories

Go is open-source, therefore, it is the part of Linux Mint 20 base repository and we can install it from there.

Open the terminal and update the apt package listing:

Now, install Go with the command:

Once Go is installed, check the installed version using the command below:

As of writing, the latest version of Go is 1.16. Since the base repositories do not always include the most current version of the application, therefore an older version of Go is installed on my Linux Mint.

Installing Go on Linux Mint 20 from the Official Tarball

Complete the below-given steps to install Go on Linux Mint 20 from the official tarball:

Step 1: Download Go official tarball
First, fire up the terminal and download the Go latest official tarball:

Step 2: Extract Go tarball
Then, extract the Go archive file in the /usr/local directory with the command below:

Step 3: Set the path variable
Next, we have to set the path environment variable value in the .bashrc file. Open the .bashrc file in the text editor:

Add the below-given line in the .bashrc file, so that the system can find the Go binary files:

Step 4: Verify the Go installation
Once the path variable is set, open the new terminal window and verify the Go installation with the command:

In the output, you can see that the latest version of Go is installed on my Linux Mint 20 system.

Getting Started with Go on Linux Mint 20

Let’s create a Go file and run the first Go program:

Run your .go file with the command:

Conclusion

We can install Go on Linux Mint 20 from the base repository and the Go tarball. This post focuses on Go installation on Linux Mint 20. Moreover, we have also created and executed our first Go program.

About the author

Kamran Sattar Awaisi

I am a software engineer and a research scholar. I like to write article and make tutorial on various IT topics including Python, Cloud Computing, Fog Computing and Deep Learning. I love to use Linux based operating systems.

Источник

How to Install GoLang (Go Programming Language) in Linux

Go (also referred to as GoLang) is an open-source and lower-level programming language designed to enable users to easily write simple, reliable, and highly efficient computer programs.

Developed in 2007 at Google by a team of programmers – Robert Griesemer, Rob Pike, and Ken Thompson, it is a compiled, statically typed language same to other system languages such as C, C++, Java, and many more.

GoLang is highly productive, and readable with support for networking and multiprocessing and it is scalable in extensive systems as well. Below is a list of a few well known open source projects developed using GoLang:

  • Docker
  • Kubernetes
  • Lime
  • InfluxDB
  • Gogs (Go Git Service) among others.
Читайте также:  Windows batch file script directory

Install GoLang in Linux Systems

1. Go to https://golang.org/dl/ and download the latest version (i.e 1.15.2) of GoLang in an archive file using wget command as follows:

2. Next, check the integrity of the tarball by verifying the SHA256 checksum of the archive file using the shasum command as below, where the flag -a is used to specify the algorithm to be used:

Important: To show that the contents of the downloaded archive file are the exact copy provided on the GoLang website, the 256-bit hash value generated from the command above as seen in the output should be the same as that provided along with the download link.

If that is the case, proceed to the next step, otherwise, download a new tarball and run the check again.

3. Then extract the tar archive files into /usr/local directory using the command below.

Where, -C specifies the destination directory..

Configuring GoLang Environment in Linux

4. First, set up your Go workspace by creating a directory

/go_projects which is the root of your workspace. The workspace is made of three directories namely:

  1. bin which will contain Go executable binaries.
  2. src which will store your source files and
  3. pkg which will store package objects.

Therefore create the above directory tree as follows:

5. Now it’s time to execute Go like the rest of Linux programs without specifying its absolute path, its installation directory must be stored as one of the values of $PATH environment variable.

Now, add /usr/local/go/bin to the PATH environment variable by inserting the line below in your /etc/profile file for a system-wide installation or $HOME/.profile or $HOME./bash_profile for user-specific installation:

Using your preferred editor, open the appropriate user profile file as per your distribution and add the line below, save the file, and exit:

6. Then, set the values of GOPATH and GOBIN Go environment variables in your user profile file (

/bash_profile ) to point to your workspace directory.

Note: If you installed GoLang in a custom directory other than the default (/usr/local/), you must specify that directory as the value of the GOROOT variable.

For instance, if you have installed GoLang in the home directory, add the lines below to your $HOME/.profile or $HOME/.bash_profile file.

7. The final step under this section is to effect the changes made to the user profile in the current bash session like so:

Verify GoLang Installation

8. Run the commands below to view your Go version and environment:

Check GoLang Version and Environment

Type the following command to display usage information for the Go tool, which manages Go source code:

9. To test your if your Go installation is working correctly, write a small Go hello world program, save the file in

/go_projects/src/hello/ directory. All your GoLang source files must end with the .go extension.

Begin by creating the hello project directory under

Then use your favorite editor to create the hello.go file:

Add the lines below in the file, save it, and exit:

10. Now, compile the program above as using go install and run it:

First GoLang Program

If you see the output showing you the message in the program file, then your installation is working correctly.

11. To run your Go binary executables like other Linux commands, add $GOBIN to your $PATH environment variable.

Reference Links: https://golang.org/

That’s it! You can now go on and learn GoLang for writing simple, reliable, and highly efficient computer programs. Are you already make use of GoLang?

Share your experience with us and many other Linux users out there via the comment section below or imaginably, you can ask a question in relation to this guide or GoLang.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

Читайте также:  Windows home basic снять ограничения

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Установка Go в Ubuntu 20.04

Язык программирования Go или как его еще называют Golang, это относительно новый язык от корпорации Google, который по своим возможностям стремится заменить Си и С++. Он создан одним из разработчиков Си и здесь уже были учтены все ошибки, допущенные при создании того языка. Go имеет улучшенную безопасность, мультипоточность, полностью кросплатформенен и многое другое. На Go можно даже писать приложения для Android.

В этой статье мы рассмотрим как выполняется установка Go в Ubuntu 20.04 и более поздних версиях. Рассмотрим установку компилятора с официального сайта или PPA, а также запустим небольшую программу чтобы проверить как все работает.

Что такое Go?

Сначала важно понять что же все-таки такое Go. Этот язык был создан сотрудниками корпорации Google в 2009 году. В этом процессе принимал участие Кен Томпсон, один из разработчиков Си. В первую очередь это компилируемый язык системного программирования, который подходит для создания высокоэффективных программ. Хотя в Go возможен запуск программ в интерпретаторе, они компилируются в объектный код и не требуют виртуальной машины.

Основные возможности языка — это строгая типизация, поддержка указателей, поддержка юникода, динамические массивы, хэш таблицы, автоматическое управление памятью, потоки для параллельного программирования, а также каналы для связи между потоками. Синтаксис Go очень похож на Си, с тем лишь отличием, что некоторые компоненты позаимствованы из других скриптовых языков. Язык постоянно развивается и получает новые возможности. А теперь рассмотрим как выполняется установка языка в Ubuntu.

Установка Go на Ubuntu

Есть несколько способов установки этого языка. Вы можете загрузить файл с бинарными файлами компилятора с официального сайта и распаковать его в какой-либо директории. Затем останется только установить несколько переменных окружения. Так вы можете получить самую последнюю версию.

1. Установка из официальных репозиториев

Сначала обновите систему до самой новой версии:

sudo apt update
sudo apt upgrade

Затем для установки достаточно выполнить такую команду:

sudo apt install golang

На этом установка завершена. Для просмотра версии выполните:

После этого вы можете переходить к настройке рабочего окружения для языка.

2. Установка из официального сайта

Как видите, на момент написания статьи в репозиториях находится версия 1.13. В то же время на официальном сайте уже можно найти версию 1.15. Если вы хотите получить именно её, надо устанавливать компилятор языка из официального сайта.

Просто выберите нужную операционную систему и дождитесь окончания загрузки. Для скачивания версии 1.15 можете воспользоваться такой командой:

После окончания загрузки расспакуйте полученный архив в папку /opt:

sudo tar -C /opt -xzf go1.15.2.linux-amd64.tar.gz

Тут тоже установка завершена. Осталось добавить путь к исполняемым файлам go в переменную среды PATH:

Теперь можно проверить версию Golang:

Если всё хорошо, отредактируйте файл /etc/environment и добавьте в строку объявления PATH путь /opt/go/bin:

Изменения будут применены только после перезагрузки.

3. Установка из PPA

В последнее время PPA один за другим перестают обновляться и поддерживать новые версии Ubuntu, но этот всё ещё работает и содержит довольно свежую версию компилятора Golang — 1.15. Для добавления PPA в систему выполните такие команды:

sudo add-apt-repository ppa:longsleep/golang-backports

Затем для установки достаточно выполнить:

sudo apt install golang

Тестирование языка Go

Особенность Go в том, что все пакеты, которые вы создаете должны находится в определённой папке. Go не будет искать пакеты сначала в текущей папке проекта, как это делается обычно, а будет пытаться их найти в папке указанной в переменной окружения GOPATH. Поэтому сначала создадим рабочую папку для исходников в домашней папке:

Дальше нужно сообщить Go, где находится наша папка для проектов, для этого с помощью GOPATH:

Эту же строку можно добавить в /etc/profile, чтобы не вводить её каждый раз. Обратите внимание, что в рабочей папке есть папка src, а уже в ней нужно создавать папки проектов, для каждого проекта отдельная папка. Дальше создадим небольшую программу, которая будет выводить только одну строчку на экран:

Читайте также:  Windows mixed reality hp reverb g2

package main
import «fmt»
func main() <
fmt.Println(«hello, world»)
>

Теперь соберем программу:

Затем программу можно выполнить такой командой:

Программу можно не только собрать, но и установить с помощью команды install:

Тогда исполняемый файл программы будет создан не в текущей папке а в данном примере в $HOME/work/bin. Если эта папка не существует, то она будет создана.

Выводы

В этой статье мы рассмотрели как выполняется установка go на ubuntu, здесь есть целых два метода и вы обязательно подберете тот, который подходит для вас больше всего. Если у вас остались вопросы, спрашивайте в комментариях!

Оцените статью:

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

5 комментариев

Рекомендую использовать Go Version Manager https://github.com/moovweb/gvm

вот такую фигню пишет:
adminofsystem@Admin-PC

/work/src/hello $ go install hello.go
go install: no install location for .go files listed on command line (GOBIN not set)
и что с этим делать?

Я вчера тоже устанавливал и настраивал GO по этой статье и тоже столкнулся с таким сообщением. Для решения сперва просто набрал GO, получил такой ответ:
Go is a tool for managing Go source code.

go command [arguments]

The commands are:

build compile packages and dependencies
clean remove object files
doc show documentation for package or symbol
env print Go environment information
bug start a bug report
fix run go tool fix on packages
fmt run gofmt on package sources
generate generate Go files by processing source
get download and install packages and dependencies
install compile and install packages and dependencies
list list packages
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet run go tool vet on packages

Use «go help [command]» for more information about a command.

Additional help topics:

c calling between Go and C
buildmode description of build modes
filetype file types
gopath GOPATH environment variable
environment environment variables
importpath import path syntax
packages description of package lists
testflag description of testing flags
testfunc description of testing functions

Use «go help [topic]» for more information about that topic.
——————————————————————————————
Здесь меня привлекла команда env и я набрал go env и получил:
GOARCH=»amd64″
GOBIN=»»
GOEXE=»»
GOHOSTARCH=»amd64″
GOHOSTOS=»linux»
GOOS=»linux»
GOPATH=»/home/user_name/work/»
GORACE=»»
GOROOT=»/usr/lib/go-1.9″
GOTOOLDIR=»/usr/lib/go-1.9/pkg/tool/linux_amd64″
GCCGO=»gccgo»
CC=»gcc»
GOGCCFLAGS=»-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build068158681=/tmp/go-build -gno-record-gcc-switches»
CXX=»g++»
CGO_ENABLED=»1″
CGO_CFLAGS=»-g -O2″
CGO_CPPFLAGS=»»
CGO_CXXFLAGS=»-g -O2″
CGO_FFLAGS=»-g -O2″
CGO_LDFLAGS=»-g -O2″
PKG_CONFIG=»pkg-config»
————————————————————
Здесь видно, что переменная GOBIN пустая. Вот поэтому. думаю я, в нашем сообщении об ошибке пишется GOBIN not set. Я у себя в ручную установил её значение в «/usr/lib/go-1.9/bin/» и стало работать. Правда, это привело к тому, что скомпилированные файлы GO помещает в этот же каталог:
$ ls -ls /usr/lib/go-1.9/bin/
итого 11016
7044 -rwxr-xr-x 1 root root 7209352 окт 31 12:38 go
2144 -rwxr-xr-x 1 root root 2194888 окт 31 12:38 gofmt
1828 -rwxr-xr-x 1 root root 1868367 дек 11 17:55 hello
А это наверно не совсем правильно. Как я понимаю, результаты компиляции должны помещаться в каталог

Смог решить эту проблему по этой статье.
Ключевой была эта строчка:
«Note: Set the GOBIN path to generate a binary file when go install is run.

export GOBIN=$HOME/work/bin»
Крч, пишем в консоль «go install hello(или другое имя вашего файла)»,
вам выдает ошибку: «go install: no install location for .go files listed on command line (GOBIN not set)»,
сразу же пишем: «export GOBIN=$HOME/work/bin».
Теперь вновь прописываем: «go install hello(или другое имя вашего файла)» и если компилятор не найдет ошибок, то ваша прога будет готова;)
Также проще запускать уже скомпилированные програмы командой: «go run hello.go»
Как у меня все выглядит в консоли:

/work/src $ go install hello.go
go install: no install location for .go files listed on command line (GOBIN not set)
do-while@NewGenius

/work/src $ export GOBIN=$HOME/work/bin
do-while@NewGenius

Источник

Оцените статью