One place for hosting & domains

      Local

      Como Instalar o Go e Configurar um Ambiente de Programação Local no Ubuntu 18.04


      Introdução

      Go é uma linguagem de programação que nasceu da frustração no Google. Os desenvolvedores precisavam escolher continuamente uma linguagem que fosse executada com eficiência, mas demoravam muito tempo para compilar ou escolher uma linguagem fácil de programar, mas que era executada de forma ineficiente em produção. O Go foi projetado para ter todas as três características disponíveis ao mesmo tempo: compilação rápida, facilidade de programação e execução eficiente em produção.

      Embora o Go seja uma linguagem de programação versátil que pode ser usada para muitos projetos de programação diferentes, ela é particularmente adequada para programas de rede/sistemas distribuídos e ganhou a reputação de ser “a linguagem da nuvem”. Ela se concentra em ajudar o programador moderno a fazer mais com um conjunto forte de ferramentas, removendo debates sobre formatação ao tornar o formato parte da especificação da linguagem, bem como ao facilitar o deploy ao compilar para um único binário. O Go é fácil de aprender, com um conjunto muito pequeno de palavras-chave, o que o torna uma ótima opção para iniciantes e igualmente para desenvolvedores experientes.

      Este tutorial irá guiá-lo pela instalação e configuração de um workspace de programação com o Go via linha de comando. Este tutorial cobrirá explicitamente o procedimento de instalação para o Ubuntu 18.04, mas os princípios gerais podem se aplicar a outras distribuições Debian Linux.

      Pré-requisitos

      Você precisará de um computador ou máquina virtual com o Ubuntu 18.04 instalado, além de ter acesso administrativo a essa máquina e uma conexão à Internet. Você pode baixar este sistema operacional através da página de releases do Ubuntu 18.04.

      Passo 1 — Configurando o Go

      Neste passo, você instalará o Go fazendo o download da versão atual da página oficial de downloads do Go.

      Para fazer isso, você vai querer encontrar a URL para o tarball do binário da versão atual. Você também vai querer anotar o hash SHA256 listado ao lado dele, pois você usará esse hash para verificar o arquivo baixado.

      Você estará concluindo a instalação e a configuração na linha de comando, que é uma maneira não gráfica de interagir com seu computador. Ou seja, em vez de clicar nos botões, você digitará texto e receberá retornos do seu computador por meio de texto também.

      A linha de comando, também conhecida como shell ou terminal, pode ajudá-lo a modificar e automatizar muitas das tarefas que você faz em um computador todos os dias e é uma ferramenta essencial para desenvolvedores de software. Existem muitos comandos de terminal para aprender que podem permitir que você faça coisas mais poderosas. Para mais informações sobre a linha de comando, confira o tutorial Introdução ao Terminal do Linux.

      No Ubuntu 18.04, você pode encontrar o aplicativo Terminal clicando no ícone do Ubuntu no canto superior esquerdo da tela e digitando terminal na barra de pesquisa. Clique no ícone do aplicativo Terminal para abri-lo. Alternativamente, você pode pressionar as teclas CTRL,ALT e T no teclado simultaneamente para abrir o aplicativo Terminal automaticamente.

      Ubuntu Terminal

      Quando o terminal estiver aberto, você instalará manualmente os binários do Go. Embora você possa usar um gerenciador de pacotes, como o apt-get, percorrer as etapas de instalação manual o ajudará a entender as alterações de configuração necessárias ao sistema para ter um workspace Go válido.

      Antes de baixar o Go, certifique-se de estar no diretório home (~):

      Use o curl para recuperar a URL do tarball que você copiou da página oficial de downloads do Go:

      • curl -O https://dl.google.com/go/go1.12.1.linux-amd64.tar.gz

      Em seguida, use sha256sum para verificar o tarball:

      • sha256sum go1.12.1.linux-amd64.tar.gz

      O hash que é exibido a partir da execução do comando acima deve corresponder ao hash que estava na página de downloads. Se não, então este não é um arquivo válido e você deve baixar o arquivo novamente.

      Output

      2a3fdabf665496a0db5f41ec6af7a9b15a49fbe71a85a50ca38b1f13a103aeec go1.12.1.linux-amd64.tar.gz

      Em seguida, extraia o arquivo baixado e instale-o no local desejado no sistema. É considerado uma boa prática mantê-lo em /usr/local:

      • sudo tar -xvf go1.12.1.linux-amd64.tar.gz -C /usr/local

      Você terá agora um diretório chamado go no diretório /usr/local. Em seguida, altere recursivamente o proprietário e o grupo deste diretório para root:

      • sudo chown -R root:root /usr/local/go

      Isso protegerá todos os arquivos e garantirá que apenas o usuário root possa executar os binários do Go.

      Nota: Embora /usr/local/go seja o local oficialmente recomendado, alguns usuários podem preferir ou exigir caminhos diferentes.

      Nesta etapa, você baixou e instalou o Go na sua máquina Ubuntu 18.04. Na próxima etapa, você configurará seu workspace de Go.

      Passo 2 — Criando seu Workspace de Go

      Você pode criar seu workspace de programação agora que o Go está instalado. O workspace do Go conterá dois diretórios em sua raiz:

      • src: O diretório que contém os arquivos-fonte do Go. Um arquivo-fonte é um arquivo que você escreve usando a linguagem de programação Go. Arquivos-fonte são usados pelo compilador Go para criar um arquivo binário executável.
      • bin: O diretório que contém executáveis compilados e instalados pelas ferramentas Go. Executáveis são arquivos binários que são executados em seu sistema e executam tarefas. Estes são normalmente os programas compilados a partir do seu código-fonte ou outro código-fonte Go baixado.

      O subdiretório src pode conter vários repositórios de controle de versão (tais como o Git, o Mercurial, e o Bazaar). Isso permite uma importação canônica de código em seu projeto. As importações canônicas são importações que fazem referência a um pacote completo, como o github.com/digitalocean/godo.

      Você verá diretórios como github.com, golang.org ou outros quando seu programa importar bibliotecas de terceiros. Se você estiver usando um repositório de código como o github.com, você também colocará seus projetos e arquivos-fonte nesse diretório. Vamos explorar esse conceito mais adiante neste passo.

      Aqui está como pode se parecer um workspace típico:

      .
      ├── bin
      │   ├── buffalo                                      # comando executável
      │   ├── dlv                                          # comando executável
      │   └── packr                                        # comando executável
      └── src
          └── github.com
              └── digitalocean
                  └── godo
                      ├── .git                            # metadados do repositório do Git
                      ├── account.go                      # fonte do pacote
                      ├── account_test.go                 # fonte do teste
                      ├── ...
                      ├── timestamp.go
                      ├── timestamp_test.go
                      └── util
                          ├── droplet.go
                          └── droplet_test.go
      

      O diretório padrão para o workspace Go a partir da versão 1.8 é o diretório home do usuário com um subdiretório go ou $HOME/go. Se você estiver usando uma versão anterior à 1.8 do Go, ainda é considerado uma boa prática usar o local $HOME/go para o seu workspace.

      Execute o seguinte comando para criar a estrutura de diretórios para o seu workspace Go:

      • mkdir -p $HOME/go/{bin,src}

      A opção -p diz ao mkdir para criar todos os subdiretórios no diretório, mesmo que eles não existam atualmente. A utilização do {bin, src} cria um conjunto de argumentos para mkdir e diz para ele criar tanto o diretóriobin quanto o diretório src.

      Isso garantirá que a seguinte estrutura de diretórios esteja em vigor:

      └── $HOME
          └── go
              ├── bin
              └── src
      

      Antes do Go 1.8, era necessário definir uma variável de ambiente local chamada $GOPATH. $GOPATH diz ao compilador onde encontrar o código-fonte importado de terceiros, bem como qualquer código-fonte local que você tenha escrito. Embora não seja mais explicitamente exigido, ainda é considerada uma boa prática, pois muitas ferramentas de terceiros ainda dependem da configuração dessa variável.

      Você pode definir seu $GOPATH adicionando as variáveis globais ao seu ~/.profile. Você pode querer adicionar isto ao arquivo .zshrc ou .bashrc de acordo com a configuração do seu shell.

      Primeiro, abra o ~/.profile com o nano ou seu editor de textos preferido:

      Configure seu $GOPATH adicionando o seguinte ao arquivo:

      ~/.profile

      export GOPATH=$HOME/go
      

      Quando o Go compila e instala ferramentas, ele as coloca no diretório $GOPATH/bin. Por conveniência, é comum adicionar o subdiretório /bin do workspace ao seu PATH no seu ~/.profile:

      ~/.profile

      export PATH=$PATH:$GOPATH/bin
      

      Isso permitirá que você execute quaisquer programas compilados ou baixados por meio das ferramentas Go em qualquer parte do sistema.

      Finalmente, você precisa adicionar o binário go ao seu PATH. Você pode fazer isso adicionando /usr/local/go/bin ao final da linha:

      ~/.profile

      export PATH=$PATH:$GOPATH/bin:/usr/local/go/bin
      

      Adicionar /usr/local/go/bin ao seu $PATH torna todas as ferramentas Go disponíveis em qualquer lugar do seu sistema.

      Para atualizar seu shell, execute o seguinte comando para carregar as variáveis globais:

      Você pode verificar se seu $PATH está atualizado usando o comando echo e inspecionando a saída:

      Você verá o seu $GOPATH/bin que aparecerá no seu diretório pessoal. Se você está logado como root, você verá /root/go/bin no caminho.

      Output

      /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/root/go/bin:/usr/local/go/bin

      Você também verá o caminho para as ferramentas Go /usr/local/go/bin:

      Output

      /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/root/go/bin:/usr/local/go/bin

      Verifique a instalação, conferindo a versão atual do Go:

      E devemos receber uma saída assim:

      Output

      go version go1.12.1 linux/amd64

      Agora que você tem a raiz do workspace criada e sua variável de ambiente $GOPATH definida, você pode criar seus projetos futuros com a seguinte estrutura de diretórios. Este exemplo assume que você está usando o github.com como seu repositório:

      $GOPATH/src/github.com/username/project
      

      Então, como um exemplo, se você estivesse trabalhando no projeto https://github.com/digitalocean/godo, ele seria armazenado no seguinte diretório:

      $GOPATH/src/github.com/digitalocean/godo
      

      Esta estrutura de projeto disponibilizará projetos com a ferramenta go get. Também ajudará a legibilidade mais tarde. Você pode verificar isso usando o comando go get e buscar a biblioteca godo:

      • go get github.com/digitalocean/godo

      Isto irá baixar o conteúdo da biblioteca godo e criar o diretório $GOPATH/src/github.com/digitalocean/godo em sua máquina.

      Você pode verificar se baixou com sucesso o pacote godo listando o diretório:

      • ll $GOPATH/src/github.com/digitalocean/godo

      Você deve ver uma saída semelhante a esta:

      Output

      drwxr-xr-x 4 root root 4096 Apr 5 00:43 ./ drwxr-xr-x 3 root root 4096 Apr 5 00:43 ../ drwxr-xr-x 8 root root 4096 Apr 5 00:43 .git/ -rwxr-xr-x 1 root root 8 Apr 5 00:43 .gitignore* -rw-r--r-- 1 root root 61 Apr 5 00:43 .travis.yml -rw-r--r-- 1 root root 2808 Apr 5 00:43 CHANGELOG.md -rw-r--r-- 1 root root 1851 Apr 5 00:43 CONTRIBUTING.md . . . -rw-r--r-- 1 root root 4893 Apr 5 00:43 vpcs.go -rw-r--r-- 1 root root 4091 Apr 5 00:43 vpcs_test.go

      Neste passo, você criou um workspace Go e configurou as variáveis de ambiente necessárias. No próximo passo, você testará o workspace com algum código.

      Passo 3 — Criando um Programa Simples

      Agora que você tem o workspace Go configurado, crie um programa “Hello, World!”. Isso garantirá que o workspace esteja configurado corretamente e também lhe dará a oportunidade de se familiarizar com o Go. Como estamos criando um único arquivo-fonte Go, e não um projeto real, não precisamos estar em nosso workspace para fazer isso.

      A partir do seu diretório home, abra um editor de texto de linha de comando, como o nano, e crie um novo arquivo:

      Escreva seu programa em seu novo arquivo:

      package main
      
      import "fmt"
      
      func main() {
          fmt.Println("Hello, World!")
      }
      

      Este código usará o pacote fmt e chamará a função Println com Hello, World! como argumento. Isso fará com que a frase Hello, World! seja impressa no terminal quando o programa for executado.

      Saia do nano pressionando as teclas CTRL e X. Quando solicitado a salvar o arquivo, pressione Y e depois ENTER.

      Ao sair do nano e retornar ao seu shell, execute o programa:

      go run hello.go
      

      O programa hello.go fará com que o terminal produza a seguinte saída:

      Output

      Hello, World!

      Nesta etapa, você usou um programa básico para verificar se seu workspace Go está configurado corretamente.

      Conclusão

      Parabéns! Neste ponto, você tem um workspace de programação Go configurado em sua máquina Ubuntu e pode começar um projeto de codificação!



      Source link

      How To Install F# and Set Up a Local Programming Environment on Ubuntu 18.04


      The author selected the Free Software Foundation to receive a donation as part of the Write for DOnations program.

      Introduction

      F# is an open-source programming language initially developed at Microsoft Research to extend .NET, Microsoft’s set of tools, libraries, and languages to build applications and services. Besides its remarkably concise syntax, F# supports multiple paradigms, meaning that it can do different types of code structuring, though it was primarily designed to take advantage of the functional programming approach.

      Adopting a specific paradigm, or a style of code, determines the way we will think and organize our programming problem solving. With an imperative approach, the design model used in languages like C++ or Java, a developer describes step-by-step how the computer must accomplish a task. It’s about writing a sequence of statements that will change memory states at the program’s execution. This works fine until we encounter some irregular situations. Consider a shared object for instance, which is used by multiple applications simultaneously. We might want to read its value at the same time that another component is modifying it. These are concurrent actions upon a memory location that can produce data inconsistency and undefined behavior.

      In functional code design, we prevent this kind of problem by minimizing the use of mutable states, or states that can change after we make them. Function is the keyword here, referring to mathematical transformations on some information provided as arguments. A functional code expresses what the program is by composing the solution as a set of functions to be executed. Typically, we build up layers of logic using functions that can return another function or take other functions as inputs.

      Functional programming with F# brings a number of benefits:

      • A more readable and expressive syntax that increases program maintainability.
      • A code less prone to breaking and easier to debug because of stateless functions that can be isolated for testing.
      • Native constructs that facilitate asynchronous programming and safer concurrency.
      • Access to all the existing tools in the .NET world including the community-shared packages.

      Choosing a Runtime

      Since F# is cross-platform, maintaining a similar execution model behavior through different operating systems is essential. .NET achieves this by means of a runtime. A runtime system is a piece of software that orchestrates the execution of a program written with a specific programming language, handling interfacing with the operating system and memory management, among other things.

      There are actually two .NET runtime implementations available on Linux: .NET Core and Mono. Historically, .NET only worked on Windows. In those days, one could resort to the community Mono project to run .NET applications on other platforms like Linux and macOS. Microsoft then launched .NET Core, a faster, modular subset of the original .NET framework, to target multiple platforms.

      At the time of this tutorial’s publication, they both can be used for building web applications or command line utilities. That said, .NET Core does not ship models to create GUI desktop applications on Linux and macOS, while Mono is the only one to support mobile and gaming platforms. It is important to know these differences since the runtime you pick will shape the programs you will build. You could also choose to have both .NET Core and Mono installed in order to account for all use cases and to make a more productive stack.

      In this tutorial, you will set up an F# programming environment on Ubuntu 18.04 using both .NET Core and Mono runtimes. You will then write some code examples to test and review build and compile methods.

      Prerequisites

      To complete this tutorial, you will need basic familiarity with the command line and a computer running Ubuntu 18.04 with a non-root user with sudo privileges.

      Step 1 — Installing F# with .NET Core

      Microsoft provides the .NET Core Software Development Kit (SDK) for F# developers. A Software Development Kit is a set of programming tools that allows programmers to produce specialized applications and adapt them to various operating systems. It traditionally includes a text editor, languages support, a runtime, and a compiler, among other components. In this step, you are going to install this SDK. But first, you will register the Microsoft repository and fetch some dependencies.

      You’ll be completing the installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

      The command line, also known as a shell or terminal, can help modify and automate many of the tasks you do on a computer every day, and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. For more information about the command line, check out the Introduction to the Linux Terminal tutorial.

      On Ubuntu 18.04, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on the keyboard at the same time to open the Terminal application automatically.

      Ubuntu Terminal

      Once you have opened the terminal, use the wget command to download a package containing some required files, the Microsoft repository configurations, and a key for server communication.

      • wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb

      Now, add the Microsoft repository and install the packages to your system using the dpkg -i instruction.

      • sudo dpkg -i packages-microsoft-prod.deb

      Next, activate the Universe repository, which on Ubuntu is a community-maintained archive of software that is free and open source. This will give you access to apt-transport-https, a dependency for enabling the Ubuntu package manager APT transport over HTTPS.

      • sudo add-apt-repository universe
      • sudo apt install apt-transport-https

      Next, update available downloads:

      Finally, install the current version of the .NET SDK. This tutorial will use version 2.2:

      • sudo apt install dotnet-sdk-2.2

      Now that you have the .NET SDK installed, a quick way to check if everything went well is to try the .NET Core command line interface (CLI), which will be available in the shell once the SDK is downloaded and installed. Display information about your .NET setup by typing this in your terminal:

      When you run a dotnet command for the first time, a text section is displayed as shown below:

      Output

      Welcome to .NET Core! --------------------- Learn more about .NET Core: https://aka.ms/dotnet-docs Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs Telemetry --------- The .NET Core tools collect usage data in order to help us improve your experience. The data is anonymous and doesn't include command-line arguments. The data is collected by Microsoft and shared with the community. You can opt-out of telemetry by setting the DOTNET_CLI_TELEMETRY_OPTOUT environment variable to '1' or 'true' using your favorite shell. Read more about .NET Core CLI Tools telemetry: https://aka.ms/dotnet-cli-telemetry ...

      This notification is about collected data, and explains that some .NET CLI commands will send usage information to Microsoft. You will disable this in a moment; for now, look at the output from dotnet --info.

      After a brief moment, the terminal will list information about your .NET installation:

      Output

      .NET Core SDK (reflecting any global.json): Version: 2.2.101 Commit: 236713b0b7 Runtime Environment: OS Name: ubuntu OS Version: 18.04 OS Platform: Linux RID: ubuntu.18.04-x64 Base Path: /usr/share/dotnet/sdk/2.2.101/ Host (useful for support): Version: 2.2.0 Commit: 1249f08fed .NET Core SDKs installed: 2.2.101 [/usr/share/dotnet/sdk] .NET Core runtimes installed: Microsoft.AspNetCore.All 2.2.0 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All] Microsoft.AspNetCore.App 2.2.0 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.NETCore.App 2.2.0 [/usr/share/dotnet/shared/Microsoft.NETCore.App] To install additional .NET Core runtimes or SDKs: https://aka.ms/dotnet-download

      Depending on the SDK version, the output may be slightly different, but this confirms that .NET Core is ready to use.

      As mentioned before, the telemetry feature allows some .NET CLI commands to send usage information to Microsoft. It is enabled by default, and can be deactivated by setting the DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1. To do so, add a new line to your .profile environment customization file by opening it in your text editor. For this tutorial, we will use nano:

      Add the following line to the end of .profile:

      ~/.profile

      . . .
      export DOTNET_CLI_TELEMETRY_OPTOUT=1
      

      Exit nano by pressing the CTRL and X keys. When prompted to save the file, press Y and then ENTER.

      You can activate the new configuration using the source command:

      From now on, telemetry will be turned off at startup.

      At this point you have .NET Core runtime, languages support, and libraries installed, allowing you to run and build some .NET applications. The dotnet CLI is also available for managing .NET source code and binaries. You could start building F# projects, but as mentioned previously, the .NET Core environment does not provide all the constructs needed to be completely cross-platform. For now you cannot use it to develop mobile applications, for example.

      In order to solve this problem, in the next step you will install F# again, but this time with Mono.

      Step 2 — Installing F# with Mono

      You can use Mono to fill in the remaining gaps in capability left by .NET Core. Mono and .NET Core are both based on the same standard library and both support .NET languages, but that is where the similarity ends. They use different runtimes, different CLIs, and different compilers, making it possible for them to be installed side by side to create a more reliable programming environment. In this section you are going to supplement your environment with the Mono tools for .NET programming and run an F# program from the command line.

      A version of Mono is available in the Ubuntu repositories, but this can be outdated. Instead, add the official Mono package repository to your package manager:

      • sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
      • echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list

      In the preceding commands, you used apt-key to retrieve keys for securing packages transferred from the official Mono repositories. You then added the Mono packages source to your repositories list.

      With a new source list added for APT, update your repositories:

      Next, download the Mono tools. Unlike .NET Core, Mono does not include F# tools, so you will download it as a separate package. Install fsharp and the mono-complete meta-package using the following command:

      • sudo apt install mono-complete fsharp

      Note: Because of the size of this download, the installation process for mono-complete may take a while.

      Once done, you will have the compiler fsharpc and an interactive shell called fsharpi or simply FSI. FSI is an environment, inside the shell, that receives user's input as an expression, evaluates it, then outputs the result and waits for another input. It is just like typing a command in the traditional shell and seeing the result, except here, inputs are F# expressions. FSI provides a fast method to test code or run scripts.

      Activate FSI with the following command:

      This will start the interactive session and replace your regular prompt with the fsharpi prompt:

      Output

      Microsoft (R) F# Interactive version 4.1 Copyright (c) Microsoft Corporation. All Rights Reserved. For help type #help;; >

      You can return to the default shell by running #quit;;. In fsharpi, each command line ends with a double semicolon.

      Let's try a simple operation using the printfn function to render a message passed as a parameter:

      You will receive the following output:

      Output

      Hello World! val it : unit = () >

      From the preceding interaction, fsharpi evaluates the expression as a unit type value. The code is then executed and the result is printed with its type.

      fsharpi can also run a file containing F# code. The script must be named with a .fsx extension and executed from the shell with the command:

      Now that you know the F# installation is working, leave the shell with:

      > #quit;;
      

      With Mono and .NET Core installed, you are now prepared to write any type of F# programs. FSI will allow you to test your code and run some scripts if needed, but executions will be slow. For your F# script to be executed, additional steps are performed to translate the source code into artifacts understandable by the processor, hence the slowness. To remedy this, in the next section you will compile your code with .NET Core, creating standalone binary files that can be immediately run by the machine.

      Step 3 — Writing and Compiling F# Programs with .NET Core

      In this step, you will compile F# source code via command line compilers provided with .NET Core. This will allow you to make your applications faster and to produce preset executable packages for specific systems, making your program easier to distribute.

      Compiling is the transformation process that turns source code into binary file. The software that accomplishes this conversion is called a compiler. .NET Core relies on the dotnet CLI to perform compiling. To demonstrate this, you are going to create a basic F# source to review the compilation cases.

      The dotnet CLI provides a complete application build toolchain. In general, an association of a command and the dotnet driver is used in the shell to complete a task. For example:

      • dotnet new will create a project
      • dotnet build will build a project and all of its dependencies
      • dotnet add package will add a package reference to a project file

      The following will create a new console project called FSharpHello. The -lang option sets the programming language you will code with while the -o option creates a directory in which to place the output.

      • dotnet new console -lang F# -o FSharpHello

      Once this is done, navigate into your newly created project directory:

      This directory contains the FSharpHello.fsproj project configuration file and the obj folder which is used to store temporary object files. There is also the Program.fs file where your default source code exists. Open it in your text editor:

      The file has been automatically filled with a Hello World program:

      Program.fs

      // Learn more about F# at http://fsharp.org
      
      open System
      
      [<EntryPoint>]
      let main argv =
          printfn "Hello World from F#!"
          0 // return an integer exit code
      

      In this code, you start importing the System module with open System, then you define the program entry point, i.e., the place where the program starts when launched from the shell. The main function will call for a Hello World message printing to the console and will stop the program (return an integer exit code).

      Exit out of the file.

      To compile and run this code, use the following from the project directory ~/FSharpHello:

      The program will run, printing the following output to the screen:

      Output

      Hello World from F#!

      Note that it took a while for this program to run, just as with the FSI. As we mentioned before, it's possible to run this faster by generating an executable, i.e., a binary file that can be run directly by the operating system. Here is how to achieve this:

      • dotnet publish -c release -r linux-x64

      This will produce the executable bin/release/netcoreapp2.2/linux-x64/publish/FSharpHello.dll file. This is a shared library that will run on a 64-bit Linux architecture. To export a generic executable for macOS systems, you would replace the linux-x64 runtime identifier (RID) with osx-x64.

      Now execute the file with the following command:

      • dotnet bin/release/netcoreapp2.2/linux-x64/publish/FSharpHello.dll

      This time, you will receive the output much quicker, since the program is already translated into binary.

      Now that you know how to compile in .NET Core, let's see how Mono compiles programs with the dedicated fsharpc command.

      Step 4 — Writing and Compiling F# Programs with Mono

      Mono's compilation process is similar to that of .NET Core, but this time there is a specific command used to compile the program. The fsharpc command is the tool, and it has been created only for compiling.

      This time, create a hello.fs file and write some F# code. First, return to your home directory:

      Next, open up a new file named hello.fs:

      Add the following line to the file:

      hello.fs

      open System
      

      As seen before, this imports the System module or namespace, giving you access to built-in system functions and objects like Console.

      Now, add in some more lines of code:

      hello.fs

      open System
      
      let hello() =
          printf "Who are you? "
          let name = Console.ReadLine()
          printfn "Oh, Hello %s!nI'm F#." name
      

      These new lines define the hello() function to read user input and print a feedback message.

      Now you can add the final lines:

      hello.fs

      open System
      
      let hello() =
          printf "Who are you? "
          let name = Console.ReadLine()
          printfn "Oh, Hello %s!nI'm F#." name
      
      hello()
      Console.ReadKey() |> ignore
      

      Here you are calling the function hello(), then using the ReadKey() method to end the program with a final keystroke.

      Save and exit the file.

      Now with the fsharpc command, use the -o flag to define the output filename and compile your hello.fs source code like this:

      • fsharpc hello.fs -o hello

      The preceding command will generate a hello executable file you can run with the mono command:

      This gives you the following output and awaits user input:

      Output

      Who are you?

      If you type in Sammy, you will get the following.

      Output

      Oh, Hello Sammy! I'm F#.

      Press a final keystroke, and the program will end.

      Congratulations! You have written and compiled your first F# program, both with Mono and .NET Core.

      Conclusion

      In this tutorial, you installed tooling for F# programming, covering both .NET Core and Mono environments. You also tested examples of F# code and built executables. These are the first steps toward learning this practical functional language.

      Next steps could be to learn the language and get in touch with the community. Also, with projects getting more complex, you might need to manage code and resources more efficiently. Package managers like NuGet or Paket are bridges to the strong ecosystem built around .NET and tools-of-choice for organizing large programs.



      Source link

      How To Install Go and Set Up a Local Programming Environment on Windows 10


      Introduction

      Go is a programming language that was born out of frustration at Google. Developers continually had to pick a language that executed efficiently but took a long time to compile, or to pick a language that was easy to program but ran inefficiently in production. Go was designed to have all three available at the same time: fast compilation, ease of programming, and efficient execution in production.

      While Go is a versatile programming language that can be used for many different programming projects, it’s particularly well suited for networking/distributed systems programs, and has earned a reputation as “the language of the cloud”. It focuses on helping the modern programmer do more with a strong set of tooling, removing debates over formatting by making the format part of the language specification, as well as making deployment easy by compiling to a single binary. Go is easy to learn, with a very small set of keywords, which makes it a great choice for beginners and experienced developers alike.

      This tutorial will guide you through installing Go on your local Windows 10 machine and setting up a programming environment via the command line.

      Prerequisites

      You will need a Windows 10 machine with administrative access that is connected to the internet.

      Step 1 — Opening and Configuring PowerShell

      You’ll be completing most of the installation and setup on a command-line interface, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well. The command line, also known as a shell, can help you modify and automate many of the tasks you do on a computer every day, and is an essential tool for software developers.

      PowerShell is a program from Microsoft that provides a command-line shell interface. Administrative tasks are performed by running cmdlets, pronounced command-lets, which are specialized classes of the .NET software framework that can carry out operations. Open-sourced in August 2016, PowerShell is now available across platforms, for both Windows and UNIX systems (including Mac and Linux).

      To find Windows PowerShell, you can right-click on the Start menu icon on the lower left-hand corner of your screen. When the menu pops up, click on Search, and then type PowerShell into the search bar. When you are presented with options, right-click on Windows PowerShell from the Desktop app. For the purposes of this tutorial, select Run as Administrator. When you are prompted with a dialog box that asks Do you want to allow this app to make changes to your PC? click on Yes.

      Once you do this, you’ll see a text-based interface that has a string of words that looks like this:

      Windows 10 PowerShell

      Switch out of the system folder by typing the following command:

      You'll then be in a home directory such as PS C:Userssammy.

      To continue with the installation process, you must first set up permissions through PowerShell. Configured to run in the most secure mode by default, there are a few levels of permissions that you can set up as an administrator:

      • Restricted is the default execution policy. Under this mode you will not be able to run scripts, and PowerShell will work only as an interactive shell.
      • AllSigned will enable you to run all scripts and configuration files that are signed by a trusted publisher, meaning that you could potentially open your machine up to the risk of running malicious scripts that happen to be signed by a trusted publisher.
      • RemoteSigned will let you run scripts and configuration files downloaded from the internet signed by trusted publishers, again opening your machine up to vulnerabilities if these trusted scripts are actually malicious.
      • Unrestricted will run all scripts and configuration files downloaded from the internet as soon as you confirm that you understand that the file was downloaded from the internet. In this case no digital signature is required, so you could be opening your machine up to the risk of running unsigned and potentially malicious scripts downloaded from the internet.

      In this tutorial you will use the RemoteSigned execution policy to set the permissions for the current user. This will allow the PowerShell to accept trusted scripts without making the permissions as broad as they would be with an Unrestricted permission. Enter the following in PowerShell:

      • Set-ExecutionPolicy -Scope CurrentUser

      PowerShell will then prompt you to provide an execution policy. Enter the following to use RemoteSigned:

      Once you press ENTER, you’ll be asked to confirm the change to the execution policy. Type the letter y to allow the changes to take effect. You can confirm that this worked by asking for the current permissions across the machine:

      • Get-ExecutionPolicy -List

      You should receive output that looks something like this:

      Output

      Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser RemoteSigned LocalMachine Undefined

      This confirms that the current user can run trusted scripts downloaded from the internet. You can now move on to downloading the files we will need to set up our Go programming environment.

      Step 2 — Installing the Package Manager Chocolatey

      A package manager is a collection of software tools that work to automate installation processes. This includes the initial installation, upgrading and configuring of software, and removing software as needed. They keep software installations in a central location and can maintain all software packages on the system in formats that are commonly used.

      Chocolatey is a command-line package manager built for Windows that works like apt-get does on Linux. Available in an open-source version, Chocolatey will help you quickly install applications and tools. You will be using it to download what you need for your development environment.

      Before installing the script, read it to confirm that you are happy with the changes it will make to your machine. To do this, use the .NET scripting framework to download and display the Chocolatey script within the terminal window.

      Start by creating a WebClient object called $script that shares internet connection settings with Internet Explorer:

      • $script = New-Object Net.WebClient

      Take a look at the available options by piping the $script object with | to the Get-Member class:

      This will return all members (properties and methods) of this WebClient object:

      Snippet of Output

      . . . DownloadFileAsync Method void DownloadFileAsync(uri address, string fileName), void DownloadFileAsync(ur... DownloadFileTaskAsync Method System.Threading.Tasks.Task DownloadFileTaskAsync(string address, string fileNa... DownloadString Method string DownloadString(string address), string DownloadString(uri address) #method we will use DownloadStringAsync Method void DownloadStringAsync(uri address), void DownloadStringAsync(uri address, Sy... DownloadStringTaskAsync Method System.Threading.Tasks.Task[string] DownloadStringTaskAsync(string address), Sy… . . .

      Looking over the output, you can identify the DownloadString method used to display the script and signature in the PowerShell window. Use this method to inspect the script:

      • $script.DownloadString("https://chocolatey.org/install.ps1")

      After inspecting the script, install Chocolatey by typing the following into PowerShell:

      • iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex

      The cmdlet iwr, or Invoke-WebRequest, allows you to extract data from the web. This will pass the script to iex, or the Invoke-Expression cmdlet, which will execute the contents of the script and run the installation for the Chocolatey package manager.

      Allow PowerShell to install Chocolatey. Once it is fully installed, you can begin installing additional tools with the choco command.

      If you need to upgrade Chocolatey at any time in the future, run the following command:

      With the package manager installed, you can install the rest of what you need for the Go programming environment.

      Step 3 — Installing the Text Editor Nano (Optional)

      In this step, you are going to install nano, a text editor that uses a command-line interface. You can use nano to write programs directly within PowerShell. This is not a compulsory step, as you can also use a text editor with a graphical user interface such as Notepad. This tutorial recommends using nano, as it will help accustom you to using PowerShell.

      Use Chocolatey to install nano:

      The -y flag automatically confirms that you want to run the script without being prompted for confirmation.

      Once nano is installed, you can use the nano command to create new text files. You will use it later in this tutorial to write your first Go program.

      Step 4 — Installing Go

      Just like you did with nano in the previous step, you will use Chocolatey to install Go:

      Note: Because go is such a small word, it has become common to use golang as a term for installing packages and when searching the internet for Go-related articles. The term Golang was born from the domain for Go, which is golang.org.

      PowerShell will now install Go, generating output within PowerShell during that process. Once the install is completed, you should see the following output:

      Output

      Environment Vars (like PATH) have changed. Close/reopen your shell to see the changes (or in powershell/cmd.exe just type `refreshenv`). The install of golang was successful. Software installed as 'msi', install location is likely default. Chocolatey installed 1/1 packages. See the log for details (C:ProgramDatachocolateylogschocolatey.log).

      With the installation finished, you’ll now confirm that Go is installed. To see the changes, close and re-open PowerShell as an Administrator, then check the version of Go available on your local machine:

      You'll receive output similar to the following:

      Output

      go version go1.12.1 windows/amd643.7.0

      Once Go is installed, you can set up a workspace for your development projects.

      Step 5 — Creating Your Go Workspace

      Now that you have Chocolatey, nano, and Go installed, you can create your programming workspace.

      The Go workspace will contain two directories at its root:

      • src: The directory that contains Go source files. A source file is a file that you write using the Go programming language. Source files are used by the Go compiler to create an executable binary file.
      • bin: The directory that contains executables built and installed by the Go tools. Executables are binary files that run on your system and execute tasks. These are typically the programs compiled by your source code or another downloaded Go source code.

      The src subdirectory may contain multiple version control repositories (such as Git, Mercurial, and Bazaar). You will see directories like github.com or golang.org when your program imports third party libraries. If you are using a code repository like github.com, you will also put your projects and source files under that directory. This allows for a canonical import of code in your project. Canonical imports are imports that reference a fully qualified package, such as github.com/digitalocean/godo.

      Here is what a typical workspace may look like:

      .
      ├── bin
      │   ├── buffalo                                      # command executable
      │   ├── dlv                                          # command executable
      │   └── packr                                        # command executable
      └── src
          └── github.com
              └── digitalocean
                  └── godo
                      ├── .git                            # Git repository metadata
                      ├── account.go                      # package source
                      ├── account_test.go                 # test source
                      ├── ...
                      ├── timestamp.go
                      ├── timestamp_test.go
                      └── util
                          ├── droplet.go
                          └── droplet_test.go
      

      The default directory for the Go workspace as of 1.8 is your user's home directory with a go subdirectory, or $HOME/go. If you are using an earlier version of Go than 1.8, it is still considered best practice to use the $HOME/go location for your workspace

      Issue the following command to navigate to the $HOME directory:

      Next, create the directory structure for your Go workspace:

      This will ensure the following directory structure is now in place:

      └── $HOME
          └── go
              ├── bin
              └── src
      

      Prior to Go 1.8, it was required to set a local environment variable called $GOPATH. While it is no longer explicitly required to do so, it is still considered a good practice as many third party tools still depend on this variable being set.

      Since you used Chocolatey for the installation, this environment variable should already be set. You can verify this with the following command:

      You should see the following output, with your username in place of sammy:

      Output

      C:Userssammygo

      When Go compiles and installs tools, it will put them in the $GOPATH/bin directory. For convenience, it's common to add the workspace's bin subdirectory to your $PATH. You can do this using the setx command in PowerShell:

      • setx PATH "$($env:path);$GOPATHbin"

      This will now allow you to run any programs you compile or download via the Go tools anywhere on your system.

      Now that you have the root of the workspace created and your $GOPATH environment variable set, you will create your future projects with the following directory structure. This example assumes you are using github.com as your repository:

      $GOPATH/src/github.com/username/project
      

      If you were working on the https://github.com/digitalocean/godo project, you would put it in the following directory:

      $GOPATH/src/github.com/digitalocean/godo
      

      Structuring your projects in this manner will make projects available with the go get tool. It will also help readability later.

      You can verify this by using the go get command to fetch the godo library:

      • go get github.com/digitalocean/godo

      Note: If you don't have git installed, Windows will open a dialog box asking if you want to install it. Click Yes to continue and follow the installation instructions.

      You can see it successfully downloaded the godo package by listing the directory:

      • ls $env:GOPATH/src/github.com/digitalocean/godo

      You will receive output similar to this:

      Output

      Directory: C:Userssammygosrcgithub.comdigitaloceangodo Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 4/10/2019 2:59 PM util -a---- 4/10/2019 2:59 PM 9 .gitignore -a---- 4/10/2019 2:59 PM 69 .travis.yml -a---- 4/10/2019 2:59 PM 1592 account.go -a---- 4/10/2019 2:59 PM 1679 account_test.go -rw-r--r-- 1 sammy staff 2892 Apr 5 15:56 CHANGELOG.md -rw-r--r-- 1 sammy staff 1851 Apr 5 15:56 CONTRIBUTING.md . . . -a---- 4/10/2019 2:59 PM 5076 vpcs.go -a---- 4/10/2019 2:59 PM 4309 vpcs_test.go

      In this step, you created a Go workspace and configured the necessary environment variables. In the next step you will test the workspace with some code.

      Step 6 — Creating a Simple Program

      Now that you have the Go workspace set up, create a simple “Hello, World!” program. This will make sure that your workspace is configured properly, and also gives you the opportunity to become more familiar with Go. Because you are creating a single Go source file, and not an actual project, you don't need to be in your workspace to do this.

      From your home directory, open up a command-line text editor, such as nano, and create a new file:

      Once the text file opens up in nano, type out your program:

      hello.go

      package main
      
      import "fmt"
      
      func main() {
          fmt.Println("Hello, World!")
      }
      

      Exit nano by pressing the CTRL and X keys. When prompted to save the file, press Y and then ENTER.

      This code will use the fmt package and call the Println function with Hello, World! as the argument. This will cause the phrase Hello, World! to print out to the terminal when the program is run.

      Once you exit out of nano and return to your shell, run the program:

      The hello.go program that you just created should cause PowerShell to produce the following output:

      Output

      Hello, World!

      In this step, you used a basic program to verify that your Go workspace is properly configured.

      Conclusion

      Congratulations! At this point you have a Go programming workspace set up on your local Windows machine and can begin a coding project!



      Source link