search
HomeBackend DevelopmentGolangpython translated to golang

python translated to golang

May 10, 2023 am 11:15 AM

Preface

Python is a widely used high-level programming language. It is easy to learn and use, has concise code, and has high development efficiency. It has been widely used in data science, machine learning and other fields. Go language is a rising star with better concurrency performance and higher code running efficiency. Therefore, when we need to improve the running efficiency of Python code or make better use of computer multi-core resources, we can use Go language to write more efficient programs.

This article mainly introduces how to translate Python code into Go language, and discusses how to design and optimize Go language programs from the perspective of Python functions.

1. Translation of Python code into Go language

Before translating Python code into Go language, you need to understand the differences and similarities between the two languages. Python is a dynamically typed language that emphasizes code readability and simplicity. Go language is a statically typed language that focuses on code maintainability and concurrent processing capabilities.

There are two ways to translate Python code into Go language. One is to manually write Go language code and implement the corresponding Go language function according to the logic of the Python program. The second is to use existing translation tools, such as py2go and transcrypt.

Manual writing of Go language code

The following introduces some examples of translating Python code into Go language code in order to better understand the relationship between the two languages.

Python code:

def fib(n):
    if n <= 1:
        return n
    else:
        return (fib(n-1) + fib(n-2))

print([fib(i) for i in range(10)])

Go language code:

package main

import "fmt"

func fib(n int) int {
    if n <= 1 {
        return n
    } else {
        return (fib(n-1) + fib(n-2))
    }
}

func main() {
    for i := 0; i < 10; i++ {
        fmt.Printf("%d ", fib(i))
    }
}

Here is another example:

Python code:

def merge_sort(lst):
    if len(lst) <= 1:
        return lst
    mid = len(lst) // 2
    left = merge_sort(lst[:mid])
    right = merge_sort(lst[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result += left[i:]
    result += right[j:]
    return result

print(merge_sort([3, 1, 4, 2, 5]))

Go Language code:

package main

import "fmt"

func mergeSort(lst []int) []int {
    if len(lst) <= 1 {
        return lst
    }
    mid := len(lst) / 2
    left := mergeSort(lst[:mid])
    right := mergeSort(lst[mid:])
    return merge(left, right)
}

func merge(left []int, right []int) []int {
    result := []int{}
    i, j := 0, 0
    for i < len(left) && j < len(right) {
        if left[i] < right[j] {
            result = append(result, left[i])
            i++
        } else {
            result = append(result, right[j])
            j++
        }
    }
    result = append(result, left[i:]...)
    result = append(result, right[j:]...)
    return result
}

func main() {
    lst := []int{3, 1, 4, 2, 5}
    fmt.Println(mergeSort(lst))
}

Use translation tools for code conversion

Using translation tools can reduce the time and workload of handwritten code. For example, use the py2go translation tool to convert the above Python code into Go language code:

Python code:

def fib(n):
    if n <= 1:
        return n
    else:
        return (fib(n-1) + fib(n-2))

print([fib(i) for i in range(10)])

Go language code:

package main

import (
    "fmt"
)

func fib(n int) int {
    if n <= 1 {
        return n
    } else {
        return (fib(n-1) + fib(n-2))
    }
}

func main() {
    var lst []int
    for i := 0; i < 10; i++ {
        lst = append(lst, fib(i))
    }
    fmt.Println(lst)
}

2. Design and optimize Go language programs from the perspective of Python functions

From the perspective of Python functions , we can optimize Go language programs in the following ways.

  1. Type declaration of initial parameters

Go language is a statically typed language, and parameter types need to be declared when the function is defined. At the same time, the parameter passing method of Go language is value passing, while the parameter passing method of Python is reference passing.

Python code:

def add(x, y):
    x.append(y)
    return x

lst = [1, 2, 3]
print(add(lst, 4))    # [1, 2, 3, 4]
print(lst)            # [1, 2, 3, 4]

Go language code:

func add(x []int, y int) []int {
    x = append(x, y)
    return x
}

func main() {
    lst := []int{1, 2, 3}
    fmt.Println(add(lst, 4))    // [1 2 3 4]
    fmt.Println(lst)            // [1 2 3]
}

In Go language, parameters need to be declared as slice types so that they can be modified in the function.

  1. Use of blank identifiers

Using blank identifiers _ in Go language can represent anonymous variables. For example, in Python, underscore _ is usually used to replace a variable name. Indicates that this variable will not be referenced in subsequent uses.

Python code:

x, _, y = (1, 2, 3)
print(x, y)    # 1 3

Go language code:

x, _, y := []int{1, 2, 3}
fmt.Println(x, y)    // 1 3

In Go language, use underscore _ to represent anonymous variables, but its scope is the current statement block. For example, when assigning a value to underscore_, the value is discarded.

  1. Interface-oriented programming

For polymorphism, Python has a built-in duck-typing feature, that is, the applicability of an object is not based on its type, but Based on the methods it has. In Go language, you can use interfaces to achieve polymorphism.

For example, in the following code, both Cat and Dog implement the Say method in the Animal interface, so there is no need to care about the actual type of the object in the Test function, only whether it implements the Animal interface.

Python code:

class Animal:
    def say(self):
        pass

class Cat(Animal):
    def say(self):
        return 'meow'

class Dog(Animal):
    def say(self):
        return 'bark'

def test(animal):
    print(animal.say())

test(Cat())    # meow
test(Dog())    # bark

Go language code:

type Animal interface {
    Say() string
}

type Cat struct {
}

func (c *Cat) Say() string {
    return "meow"
}

type Dog struct {
}

func (d *Dog) Say() string {
    return "bark"
}

func Test(animal Animal) {
    fmt.Println(animal.Say())
}

func main() {
    Test(&Cat{})    // meow
    Test(&Dog{})    // bark
}
  1. Supports optional parameters and default parameters

In Python, The writing method that supports optional parameters and default parameters is very flexible. You can specify default values ​​in the function definition, or use args and *kwargs to pass optional parameters.

Python code:

def func(a, b=10, *args, **kwargs):
    print(a, b)
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

func(1)    # 1 10
func(2, 3)    # 2 3
func(4, 5, 6, 7, eight=8, nine=9)    # 4 5 6 7 eight 8 nine 9

In the Go language, due to the support for function overloading, the parameter list of a function can define different types of parameters as needed. For example, in the following code, overloading is used to implement optional parameters and default values.

Go language code:

func Func(a int, b int) {
    fmt.Println(a, b)
}

func Func2(a int, b int, args ...int) {
    fmt.Println(a, b)
    for _, arg := range args {
        fmt.Println(arg)
    }
}

func Func3(a int, kwargs map[string]int) {
    fmt.Println(a)
    for key, value := range kwargs {
        fmt.Println(key, value)
    }
}

func main() {
    Func(1, 10)    // 1 10
    Func(2, 3)    // 2 3
    Func2(4, 5, 6, 7)    // 4 5 6 7
    kwargs := map[string]int{"eight": 8, "nine": 9}
    Func3(4, kwargs)    // 4 eight 8 nine 9
}

Summary

This article introduces how to convert Python code into Go language code, and from the perspective of Python functions, discusses how to declare parameters Types, using whitespace identifiers, interface-oriented programming, and overloading to implement optional parameters and default values ​​are ways to optimize Go language programs. Both Python and Go languages ​​have their own characteristics, advantages and disadvantages, and the specific choice of which language needs to be considered based on the specific situation. Finally, thank you for reading!

The above is the detailed content of python translated to golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Learn Go String Manipulation: Working with the 'strings' PackageLearn Go String Manipulation: Working with the 'strings' PackageMay 09, 2025 am 12:07 AM

Go's "strings" package provides rich features to make string operation efficient and simple. 1) Use strings.Contains() to check substrings. 2) strings.Split() can be used to parse data, but it should be used with caution to avoid performance problems. 3) strings.Join() is suitable for formatting strings, but for small datasets, looping = is more efficient. 4) For large strings, it is more efficient to build strings using strings.Builder.

Go: String Manipulation with the Standard 'strings' PackageGo: String Manipulation with the Standard 'strings' PackageMay 09, 2025 am 12:07 AM

Go uses the "strings" package for string operations. 1) Use strings.Join function to splice strings. 2) Use the strings.Contains function to find substrings. 3) Use the strings.Replace function to replace strings. These functions are efficient and easy to use and are suitable for various string processing tasks.

Mastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMay 09, 2025 am 12:02 AM

ThebytespackageinGoisessentialforefficientbyteslicemanipulation,offeringfunctionslikeContains,Index,andReplaceforsearchingandmodifyingbinarydata.Itenhancesperformanceandcodereadability,makingitavitaltoolforhandlingbinarydata,networkprotocols,andfileI

Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor