search
HomeBackend DevelopmentGolangConvert structure to CSV string
Convert structure to CSV stringFeb 09, 2024 pm 03:15 PM
code readability

将结构转换为 CSV 字符串

php editor Youzi will introduce you how to convert the data structure into a CSV string in this article. CSV (Comma Separated Values) is a commonly used file format used to store tabular data. By converting the data structure into a CSV string, you can conveniently export the data to other tools such as Excel for processing and analysis. In this article, we will explore the methods and techniques to implement this process using the PHP programming language. Whether you are a beginner or an experienced developer, this article will provide you with helpful guidance and sample code to help you accomplish this task with ease.

Question content

I have a structure that is scanned after the database responds as shown below. Each field is the same len(). I want to take this structure and generate a csv delimited string/

package main

import "fmt"

type data struct {
    id   []string
    col1 []float64
    col2 []float64
}

func main() {
    d := &data{
        id:   []string{"id_1", "id_1", "id_1", "id_1"},
        col1: []float64{340.384926, 321.385028, 520.341473, 500.385473},
        col2: []float64{123.285031, 4087.284675, -8958.284216, -7612.283668},
    }
    fmt.printf("%+v", d)
}

I want to loop through a structure that I think I can use reflect and then use the structure field names as headers and the values ​​as the individual columns of that header to construct a csv string like the following, consisting of a separated by commas.

`
id,col1,col2
id_1,340.384926,123.285031
id_1,321.385028,4087.284675
id_1,520.341473,-8958.284216
id_1,500.385473,-7612.283668
`

What is an efficient way to achieve this?

Workaround

If possible, avoid using reflect iterating structures as it may cause performance degradation and code readability Reduced sex. Don't fall into the xy problem - the requirement here is to convert the data structure into a csv string (y problem), but the x problem here is to avoid using data etc. Structural types as a starting point.

Many golang packages that operate on csv prefer:

However, if the data type is unavoidable, you can first write a function to convert data to [][]string while avoiding reflect

func transformdatato2dslice(d data) [][]string {

    numrows := len(d.id)
    result := make([][]string, numrows+1)

    // add header row
    result[0] = []string{"id", "col1", "col2"}

    // add data rows
    for i := 0; i < numrows; i++ {
        result[i+1] = []string{d.id[i],
            strconv.formatfloat(d.col1[i], 'f', -1, 64),
            strconv.formatfloat(d.col2[i], 'f', -1, 64),
        }
    }

    return result
}

Next, use the w.writeall() method in encoding/csv to easily convert [][]string to csv

func main() {

    d := data{
        id:   []string{"id_1", "id_1", "id_1", "id_1"},
        col1: []float64{340.384926, 321.385028, 520.341473, 500.385473},
        col2: []float64{123.285031, 4087.284675, -8958.284216, -7612.283668},
    }

    d2dslice := transformdatato2dslice(d)

    // fmt.printf("%+v", d2dslice)
    // [[id, col1, col2],
    // [id_1, 340.384926, 123.285031],
    // [id_1, 321.385028, 4087.284675],
    // [id_1, 520.341473, -8958.284216],
    // [id_1,500.385473,-7612.283668]]

    w := csv.newwriter(os.stdout)
    w.writeall(d2dslice)

    if err := w.error(); err != nil {
        log.fatalln("error writing csv:", err)
    }

    // stdout:
    // id,col1,col2
    // id_1,340.384926,123.285031
    // id_1,321.385028,4087.284675
    // id_1,520.341473,-8958.284216
    // id_1,500.385473,-7612.283668
}

Run the above program here: go-playground

To write the csv to a string variable, pass in the buffer:

buf := new(bytes.Buffer)
    w := csv.NewWriter(buf)
    w.WriteAll(d2dslice)

    if err := w.Error(); err != nil {
        log.Fatalln("error writing csv:", err)
    }

    csvString := buf.String()

    fmt.Printf("%T\n", csvString)  // print the variable type
    // string

    fmt.Printf("%+v\n", csvString) // print the variable value
    // id,col1,col2
    // id_1,340.384926,123.285031
    // id_1,321.385028,4087.284675
    // id_1,520.341473,-8958.284216
    // id_1,500.385473,-7612.283668

The above is the detailed content of Convert structure to CSV string. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
PyCharm主题推荐:优雅的代码,从优秀的主题开始PyCharm主题推荐:优雅的代码,从优秀的主题开始Feb 21, 2024 pm 04:27 PM

在编程的世界里,一个优秀的开发工具是程序员们必不可少的良师益友。PyCharm作为一款功能强大的Python集成开发环境,在市场上享有极高的声誉。它提供了丰富的功能,包括代码自动补全、调试器、版本控制工具等,帮助开发者提高开发效率,优化代码质量。然而,作为一个开发工具,PyCharm的界面和主题设计也是至关重要的。一个舒适、美观的界面可以让开发者在编写代码时

将结构转换为 CSV 字符串将结构转换为 CSV 字符串Feb 09, 2024 pm 03:15 PM

我有一个在数据库响应后被扫描的结构,如下所示。每个字段都是相同的len()。我想采用这个结构并生成一个csv分隔字符串/packagemainimport"fmt"typedatastruct{id[]stringcol1[]float64col2[]float64}funcmain(){d:=&data{id:[]string{"id_1","id_1","id_1","id_1"},

命名Java变量时使用中文的优点和缺点命名Java变量时使用中文的优点和缺点Feb 18, 2024 am 10:14 AM

使用中文命名Java变量的优缺点在Java编程中,我们通常使用英文来命名变量、方法和类等标识符。然而,有时候我们也可以考虑使用中文作为标识符的一部分。本文将探讨使用中文命名Java变量的优缺点,并给出一些具体的代码示例。优点一:提高代码可读性使用中文命名Java变量可以使代码更易理解和阅读。毕竟,我们的大脑对于中文的理解和识别要比英文更为自然和流畅。对于非英

解释Python是一种解释型语言的原因解释Python是一种解释型语言的原因Sep 17, 2023 pm 10:41 PM

Python是一种通用解释型、交互式、面向对象的高级编程语言。Python在运行时由解释器进行处理。在执行程序之前不需要编译程序。这与PERL和PHP类似。执行步骤Step1-Python源代码由编码器编写。文件扩展名:.py第2步-编码器编写的Python源代码被编译为Python字节码。在此过程中,将创建一个扩展名为.pyc的文件。步骤3-虚拟机执行.pyc扩展文件。考虑虚拟机是Python的运行时引擎。这是Python程序运行的地方。因此,Python解释器包含了程序编译的过程,程序编译为

比较JPA和MyBatis:开发效率和灵活性的对比比较JPA和MyBatis:开发效率和灵活性的对比Feb 20, 2024 am 09:54 AM

JPA和MyBatis:开发效率和灵活性的较量,需要具体代码示例引言:在现代软件开发领域,数据持久化层是一个至关重要的组成部分。为了提高开发效率和灵活性,开发者常常需要选择一个适合项目需求的ORM(对象关系映射)框架。JPA(Java持久化API)和MyBatis是目前广泛使用的两个框架,具备各自的优势和特点。本文将对比这两个框架的开发效率和灵活性,并提供

PyCharm插件安装指南:详细步骤大揭秘!PyCharm插件安装指南:详细步骤大揭秘!Feb 22, 2024 am 09:30 AM

PyCharm插件安装指南:详细步骤大揭秘!PyCharm是一款功能强大的Python集成开发环境,它的灵活性和可扩展性使得用户可以根据自己的需求安装各种插件来增强开发体验。本文将详细介绍如何在PyCharm中安装插件,以及常用插件的安装步骤和示例代码。一、PyCharm插件安装步骤:打开PyCharm并进入File->Settings菜单;在Se

应用与优化:实际项目中的MyBatis注解动态SQL应用与优化:实际项目中的MyBatis注解动态SQLFeb 19, 2024 am 09:55 AM

MyBatis注解动态SQL在实际项目中的应用与优化引言:MyBatis是一款优秀的持久层框架,它提供了多种SQL映射的方式,包括XML配置文件和注解。其中注解动态SQL是MyBatis的一项强大的功能,可以在运行时根据条件动态生成SQL语句,适用于处理复杂的业务逻辑。本文将介绍MyBatis注解动态SQL在实际项目中的应用,同时分享一些优化技巧与代码示例。

提高代码可读性:Python常见的变量命名规则解读提高代码可读性:Python常见的变量命名规则解读Jan 20, 2024 am 08:01 AM

掌握Python中常见的变量命名规则,提升代码可读性,需要具体代码示例Python作为一门简洁而强大的编程语言,其代码可读性十分重要。变量是代码中最基本的元素之一,良好的变量命名规则可以帮助开发者更好地理解和阅读代码。本文将介绍Python中常见的变量命名规则,并提供具体的代码示例,帮助读者掌握如何提升代码的可读性。一、变量命名规则使用有意义的变量名:变量名

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.